Skip to content

Consolidate Windows CentralProcessor tick query into common base (JNA/FFM dedup) - #3389

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:windows-cp-common-base
Jun 13, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:windows-cp-common-base

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Jun 13, 2026 •

Copy link
Copy Markdown
Member

Summary

  • queryProcessorCpuLoadTicks() was duplicated nearly verbatim between WindowsCentralProcessorJNA and WindowsCentralProcessorFFM, differing only in the perfmon driver call.
  • Move it — plus the memoized processorUtilityCounters supplier and the initial-counter bootstrap block — into the WindowsCentralProcessor base, which already owns the related utility-counter state (initialUtilityCounters, lazilyCalculateMultiplier, processTickData).
  • Two thin abstract driver hooks bridge the backends: queryProcessorCapacityCounters() (the memoized utility source) and queryProcessorCounters() (the non-utility tick source). The previously-abstract queryProcessorUtilityCounters() becomes a concrete delegate.
  • JNA and FFM subclasses keep only their native-specific code (registry/WMI processor id, NT power frequencies, system ticks, load average, context switches, interrupts). Eliminates ~70 duplicated lines.

Test plan

  • All pre-commit checks pass locally (spotless, checkstyle, forbiddenapis, javadoc) plus a clean full-reactor build
  • JNA==FFM parity verified by the windows-latest (+ JNA==FFM) CI job (cannot be exercised locally on non-Windows)

Summary by CodeRabbit

  • Performance

    • Windows CPU utility queries now use intelligent caching (300ms minimum), reducing system overhead and improving performance.
    • Optimized processor capacity and load tick queries for Windows platforms.
  • Refactor

    • Consolidated CPU counter query logic across Windows implementations for better maintainability and consistency.

queryProcessorCpuLoadTicks() was duplicated nearly verbatim between the
JNA and FFM subclasses, differing only in the perfmon driver call. Move
it, the memoized processorUtilityCounters supplier, and the initial-
counter bootstrap into the WindowsCentralProcessor base (which already
owns the related utility-counter state and processTickData), behind two
thin driver hooks: queryProcessorCapacityCounters() and
queryProcessorCounters(). The previously-abstract queryProcessorUtility-
Counters() becomes a concrete delegate. Eliminates ~70 duplicated lines;
the JNA and FFM subclasses keep only their native-specific code.
@coderabbitai

coderabbitai Bot commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR refactors Windows CPU counter querying to centralize memoization logic in the base WindowsCentralProcessor class and introduces a new contract method queryProcessorCapacityCounters() that both JNA and FFM implementations must fulfill. The base class now handles caching with a 300ms minimum elapsed time, while platform implementations simply provide counter data through the new abstract method.

Changes

Windows CPU Counter Query Architecture Refactoring

Layer / File(s) Summary
Base class memoization and contract refactoring
oshi-common/src/main/java/oshi/hardware/common/platform/windows/WindowsCentralProcessor.java
Imports add memoization utilities. A memoized Supplier for utility/capacity ticks is initialized on construction (when USE_CPU_UTILITY is enabled), capturing initial counter values. The abstract queryProcessorUtilityCounters() method becomes concrete and derives data from a new abstract queryProcessorCapacityCounters() method. CPU load tick querying pulls from memoized data instead of querying directly on each call.
JNA implementation alignment
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsCentralProcessorJNA.java
Removes local memoization field and initializer block, eliminates the queryProcessorCpuLoadTicks() and queryProcessorUtilityCounters() overrides, and implements the new queryProcessorCapacityCounters() and queryProcessorCounters() methods that delegate to ProcessorInformationJNA and return (instances, counters) pairs.
FFM implementation alignment
oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsCentralProcessorFFM.java
Removes memoization-related imports and eliminates the queryProcessorCpuLoadTicks() and queryProcessorUtilityCounters() overrides. Implements the new queryProcessorCapacityCounters() and queryProcessorCounters() abstract methods to fulfill the base class contract and delegate tick assembly logic upward.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 A rabbit hops through Windows ticks so fast,
But once-per-call queries don't long last.
Now memoized at base, the counters cache,
While platform helpers fetch—a speedy dash!
Abstraction flows, implementations align,
Three classes dance—refactored, clean, divine! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: consolidating duplicated Windows CentralProcessor tick query logic into a common base class to reduce code duplication between JNA and FFM implementations.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
oshi-common/src/main/java/oshi/hardware/common/platform/windows/WindowsCentralProcessor.java (1)

54-64: Defer queryProcessorCapacityCounters() call during initialization to avoid constructor-time virtual dispatch
WindowsCentralProcessor’s instance initializer calls processorUtilityCounters.get() (which invokes queryProcessorCapacityCounters() virtually) while the object is still being constructed. JNA/FFM overrides are currently pure static delegates, so this is safe today, but it creates a fragile base-class contract: a future backend that touches instance state in queryProcessorCapacityCounters() could break during partial construction. Since queryProcessorCpuLoadTicks() directly reads getInitialUtilityCounters() to populate the init* lists under USE_CPU_UTILITY, any refactor should lazily initialize initialUtilityCounters before those reads (e.g., at the start of queryProcessorCpuLoadTicks()).

♻️ Possible shape
-    {
-        // Store the initial query and start the memoizer expiration
-        if (USE_CPU_UTILITY) {
-            setInitialUtilityCounters(processorUtilityCounters.get().getB());
-        }
-    }
+    private void ensureInitialUtilityCounters() {
+        if (USE_CPU_UTILITY && getInitialUtilityCounters() == null) {
+            setInitialUtilityCounters(processorUtilityCounters.get().getB());
+        }
+    }

Then call ensureInitialUtilityCounters() before reading the initial lists in queryProcessorCpuLoadTicks().

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@oshi-common/src/main/java/oshi/hardware/common/platform/windows/WindowsCentralProcessor.java`
around lines 54 - 64, The instance initializer currently calls
processorUtilityCounters.get() (which invokes queryProcessorCapacityCounters())
during construction; defer that call by removing the get() call from the
initializer and instead add a private ensureInitialUtilityCounters() that checks
whether getInitialUtilityCounters() is populated and if not invokes
processorUtilityCounters.get() and calls setInitialUtilityCounters(...) with the
result; then call ensureInitialUtilityCounters() at the start of
queryProcessorCpuLoadTicks() (before any reads of the init* lists) so
initialUtilityCounters are lazily initialized and no virtual dispatch occurs
during object construction. Reference symbols: processorUtilityCounters,
queryProcessorCapacityCounters, setInitialUtilityCounters,
getInitialUtilityCounters, ensureInitialUtilityCounters (new), and
queryProcessorCpuLoadTicks.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In
`@oshi-common/src/main/java/oshi/hardware/common/platform/windows/WindowsCentralProcessor.java`:
- Around line 54-64: The instance initializer currently calls
processorUtilityCounters.get() (which invokes queryProcessorCapacityCounters())
during construction; defer that call by removing the get() call from the
initializer and instead add a private ensureInitialUtilityCounters() that checks
whether getInitialUtilityCounters() is populated and if not invokes
processorUtilityCounters.get() and calls setInitialUtilityCounters(...) with the
result; then call ensureInitialUtilityCounters() at the start of
queryProcessorCpuLoadTicks() (before any reads of the init* lists) so
initialUtilityCounters are lazily initialized and no virtual dispatch occurs
during object construction. Reference symbols: processorUtilityCounters,
queryProcessorCapacityCounters, setInitialUtilityCounters,
getInitialUtilityCounters, ensureInitialUtilityCounters (new), and
queryProcessorCpuLoadTicks.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: ce05ae4a-1a98-4d97-a9d9-d6121a8562f9

📥 Commits

Reviewing files that changed from the base of the PR and between a5ad114 and fa5686c.

📒 Files selected for processing (3)
  • oshi-common/src/main/java/oshi/hardware/common/platform/windows/WindowsCentralProcessor.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsCentralProcessorFFM.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsCentralProcessorJNA.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (18)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 26, windows-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 26, ubuntu-latest
  • GitHub Check: Test JDK 21, ubuntu-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 26, macos-latest
  • GitHub Check: Test JDK 25, FreeBSD (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: Test JDK 25, OpenBSD (+ JNA==FFM)
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Test JDK 25, OpenIndiana (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (3)
📚 Learning: 2026-04-06T04:45:47.644Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3121
File: oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java:53-53
Timestamp: 2026-04-06T04:45:47.644Z
Learning: In the oshi/oshi project, only interfaces and classes in the root packages `oshi`, `oshi.hardware`, and `oshi.software.os` are considered the public API. Code in subpackages that represent specific implementations/platforms (e.g., `oshi.software.os.linux`, `oshi.hardware.platform.linux`, and similar subpackages) is implementation detail. When reviewing, do not treat changes to classes in these platform-specific subpackages as public API breaks (for example: making `LinuxOperatingSystem` abstract, narrowing constructor visibility, or adding/removing abstract methods should not be flagged as breaking public API).

Applied to files:

  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsCentralProcessorJNA.java
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/hardware/common/platform/windows/WindowsCentralProcessor.java
📚 Learning: 2026-04-12T19:34:56.879Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:34:56.879Z
Learning: In OSHI’s Java platform implementations, `PhysicalProcessor.getEfficiency()` / `EfficiencyClass` follow the same convention as Windows `PROCESSOR_RELATIONSHIP.EfficiencyClass`: a *higher* numeric efficiency class value represents *greater performance* and *less efficiency* (typically P-cores higher than E-cores). When reviewing, do not treat cases where P-cores are assigned higher efficiency/class values as a bug—this is intentional cross-platform consistency.

Applied to files:

  • oshi-common/src/main/java/oshi/hardware/common/platform/windows/WindowsCentralProcessor.java
🔇 Additional comments (3)
oshi-common/src/main/java/oshi/hardware/common/platform/windows/WindowsCentralProcessor.java (1)

179-262: LGTM!

oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsCentralProcessorJNA.java (1)

277-284: LGTM!

oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsCentralProcessorFFM.java (1)

307-315: LGTM!

@codecov

codecov Bot commented Jun 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.11321% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 75.14%. Comparing base (a5ad114) to head (fa5686c).

Files with missing lines Patch % Lines
...mmon/platform/windows/WindowsCentralProcessor.java 97.95% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3389      +/-   ##
============================================
- Coverage     75.19%   75.14%   -0.05%     
  Complexity       76       76              
============================================
  Files           578      578              
  Lines         21502    21455      -47     
  Branches       3563     3560       -3     
============================================
- Hits          16169    16123      -46     
+ Misses         3311     3305       -6     
- Partials       2022     2027       +5     
Flag Coverage Δ
freebsd 26.34% <0.00%> (+0.06%) ⬆️
linux 30.87% <0.00%> (+0.06%) ⬆️
macos 31.25% <0.00%> (+0.06%) ⬆️
openbsd 25.74% <0.00%> (+0.05%) ⬆️
solaris 27.89% <0.00%> (+0.05%) ⬆️
windows 39.48% <98.11%> (-0.13%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@dbwiddis
dbwiddis merged commit 6156ca4 into oshi:master Jun 13, 2026
23 checks passed
@dbwiddis
dbwiddis deleted the windows-cp-common-base branch June 13, 2026 07:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant