Skip to content

Add NativeHandle AutoCloseable wrapper for native resource cleanup - #3290

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:add-native-handle-autocloseable
May 23, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:add-native-handle-autocloseable

Conversation

@dbwiddis

@dbwiddis dbwiddis commented May 23, 2026 •

Copy link
Copy Markdown
Member

Introduce NativeHandle, a lightweight AutoCloseable wrapper around native MemorySegment handles that ensures proper cleanup via try-with-resources. This eliminates error-prone manual finally blocks for native handle lifecycle management.

NativeHandle

  • Wraps a MemorySegment with a ThrowingCloser callback
  • Skips close if handle is null or zero-address
  • Logs and suppresses exceptions from the closer
  • Fully tested with unit tests

Reference migrations (Windows)

Simple single-handle cases migrated as examples:

  • WindowsFileSystemFFM.getLocalVolumes() — FindVolumeClose
  • WindowsCentralProcessorFFM registry methods — RegCloseKey
  • WindowsOperatingSystemFFM.enableDebugPrivilege() — CloseHandle
  • WindowsOperatingSystemFFM.queryServicesFFM() — CloseServiceHandle
  • WindowsOSProcessFFM.getAffinityMask() — CloseHandle

Future PRs

  • PR 2: Migrate remaining Windows + nested Linux handle patterns
  • PR 3: macOS (IOObject/CFTypeRef → AutoCloseable)

Summary by CodeRabbit

  • Refactor

    • Improved Windows native resource handling across platform components for more reliable cleanup and fewer resource leaks; safer automatic handle management reduces spurious errors during teardown.
  • Tests

    • Added tests validating handle cleanup semantics, idempotent close behavior, and robust suppression of errors during resource release.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 23, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 6fd2a2b8-8ac5-4be5-bf89-ded79dc296ae

📥 Commits

Reviewing files that changed from the base of the PR and between f403b28 and f348629.

📒 Files selected for processing (6)
  • oshi-core-ffm/src/main/java/oshi/ffm/NativeHandle.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsCentralProcessorFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsFileSystemFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java
  • oshi-core-ffm/src/test/java/oshi/ffm/NativeHandleTest.java
📜 Recent 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). (11)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Analyze (java)
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (6)
oshi-core-ffm/src/main/java/oshi/ffm/NativeHandle.java (1)

37-45: LGTM!

Also applies to: 51-54, 63-65, 81-83, 90-98

oshi-core-ffm/src/test/java/oshi/ffm/NativeHandleTest.java (1)

20-29: LGTM!

Also applies to: 31-38, 40-47, 49-61, 63-72, 74-77

oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java (1)

52-52: LGTM!

Also applies to: 102-103, 110-118, 155-155

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

38-38: LGTM!

Also applies to: 124-124, 129-130, 404-405, 409-410, 426-427, 431-432

oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsFileSystemFFM.java (1)

34-34: LGTM!

Also applies to: 161-161

oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java (1)

52-52: LGTM!

Also applies to: 86-87, 90-90


📝 Walkthrough

Walkthrough

A new NativeHandle AutoCloseable wrapper abstracts native MemorySegment lifetime management with a provided closer callback. The pattern is applied across four Windows FFM classes to replace manual try/finally resource cleanup with try-with-resources blocks for registry keys, volume handles, process handles, and service manager handles.

Changes

NativeHandle Wrapper and Adoption

Layer / File(s) Summary
NativeHandle wrapper abstraction and tests
oshi-core-ffm/src/main/java/oshi/ffm/NativeHandle.java, oshi-core-ffm/src/test/java/oshi/ffm/NativeHandleTest.java
NativeHandle is an AutoCloseable wrapper that holds a MemorySegment and invokes a ThrowingCloser callback on close, skipping null/zero addresses and suppressing logged exceptions. Tests verify close behavior for non-null, null, zero-address handles, and exception suppression.
Registry handle cleanup in WindowsCentralProcessorFFM
oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsCentralProcessorFFM.java
Three registry-querying methods (queryProcessorId, registryGetString, registryGetDword) wrap opened registry keys with NativeHandle for automatic closure via try-with-resources, replacing prior manual RegCloseKey finally blocks.
Volume handle cleanup in WindowsFileSystemFFM
oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsFileSystemFFM.java
The volume handle from FindFirstVolume is wrapped in a NativeHandle with FindVolumeClose closer, replacing the prior explicit finally block that manually called Kernel32FFM.FindVolumeClose.
Process handle cleanup in WindowsOSProcessFFM
oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
getAffinityMask() wraps the process handle from Kernel32FFM.OpenProcess in a NativeHandle with CloseHandle closer via try-with-resources, removing the prior manual finally block.
Token and service handle cleanup in WindowsOperatingSystemFFM
oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java
enableDebugPrivilege() wraps process token handles and queryServicesFFM() wraps the Service Control Manager handle with NativeHandle try-with-resources blocks, replacing prior manual finally-based cleanup for both token and service handles.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • oshi/oshi#3126: Introduced the WindowsOSProcessFFM class with the process handle open/close logic that this PR refactors to use NativeHandle.

Poem

🐰 I nibbled at handles, tied up with care,
Wrapped them in blankets of try-with-resources fair.
Reg keys and volumes, tokens set free,
One small closer hop, and no leaks for me. 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 31.58% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: introducing NativeHandle as an AutoCloseable wrapper for native resource cleanup, which is the primary focus of this PR.
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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
oshi-core-ffm/src/test/java/oshi/ffm/NativeHandleTest.java (1)

18-60: ⚡ Quick win

Add regression tests for idempotent close and null closer contract.

Current tests miss two high-value guards: repeated close() should not re-run the closer, and null closer should fail fast at construction.

Suggested test additions
+import static org.junit.jupiter.api.Assertions.assertThrows;
@@
 import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicReference;
@@
     void testCloserExceptionIsSuppressed() {
@@
         assertThat(closedWith.get(), is(fakeHandle));
     }
+
+    `@Test`
+    void testCloseIsIdempotent() {
+        AtomicInteger closeCount = new AtomicInteger(0);
+        MemorySegment fakeHandle = MemorySegment.ofAddress(0x4321);
+        NativeHandle h = NativeHandle.of(fakeHandle, seg -> closeCount.incrementAndGet());
+        h.close();
+        h.close();
+        assertThat(closeCount.get(), is(1));
+    }
+
+    `@Test`
+    void testNullCloserThrows() {
+        MemorySegment fakeHandle = MemorySegment.ofAddress(0x9999);
+        assertThrows(NullPointerException.class, () -> NativeHandle.of(fakeHandle, null));
+    }
 }
🤖 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-core-ffm/src/test/java/oshi/ffm/NativeHandleTest.java` around lines 18 -
60, Tests are missing checks for two contracts: NativeHandle.close() must be
idempotent (calling close() multiple times should only invoke the provided
closer once) and NativeHandle.of(...) must reject a null closer immediately
(throw at construction). Add a test that creates a NativeHandle via
NativeHandle.of(handle, closer) where the closer increments an AtomicInteger,
call close() on the handle multiple times (or exit try-with-resources then call
close() again) and assert the counter == 1; and add a test that calls
NativeHandle.of(someHandle, null) and asserts that the constructor throws (e.g.,
NullPointerException) rather than allowing a null closer.
🤖 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.

Inline comments:
In `@oshi-core-ffm/src/main/java/oshi/ffm/NativeHandle.java`:
- Around line 48-51: The NativeHandle constructor and close logic must fail fast
on a null ThrowingCloser and make close idempotent to prevent double-closing
native resources: in the NativeHandle(MemorySegment handle, ThrowingCloser
closer) constructor validate closer != null and throw
NPE/IllegalArgumentException immediately if null, store it otherwise; in the
close() method on class NativeHandle add a volatile/atomic boolean (e.g., closed
or closedFlag as AtomicBoolean) and only invoke closer.close(handle) when
transitioning from false to true so subsequent close() calls are no-ops, and
ensure any exceptions from closer.close are propagated or wrapped consistently;
update references to the closer field and close() method accordingly.

---

Nitpick comments:
In `@oshi-core-ffm/src/test/java/oshi/ffm/NativeHandleTest.java`:
- Around line 18-60: Tests are missing checks for two contracts:
NativeHandle.close() must be idempotent (calling close() multiple times should
only invoke the provided closer once) and NativeHandle.of(...) must reject a
null closer immediately (throw at construction). Add a test that creates a
NativeHandle via NativeHandle.of(handle, closer) where the closer increments an
AtomicInteger, call close() on the handle multiple times (or exit
try-with-resources then call close() again) and assert the counter == 1; and add
a test that calls NativeHandle.of(someHandle, null) and asserts that the
constructor throws (e.g., NullPointerException) rather than allowing a null
closer.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 6e72586d-f6b3-4da0-b41f-bc6eb8fbed88

📥 Commits

Reviewing files that changed from the base of the PR and between 71596de and f403b28.

📒 Files selected for processing (6)
  • oshi-core-ffm/src/main/java/oshi/ffm/NativeHandle.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsCentralProcessorFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsFileSystemFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java
  • oshi-core-ffm/src/test/java/oshi/ffm/NativeHandleTest.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). (8)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Analyze (java)
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: JMH Benchmarks, ubuntu-latest
🔇 Additional comments (4)
oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsCentralProcessorFFM.java (1)

38-38: LGTM!

Also applies to: 124-130, 404-410, 426-432

oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsFileSystemFFM.java (1)

34-35: LGTM!

Also applies to: 161-162

oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsOSProcessFFM.java (1)

52-53: LGTM!

Also applies to: 86-90

oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsOperatingSystemFFM.java (1)

52-53: LGTM!

Also applies to: 102-117, 155-156

@codecov

codecov Bot commented May 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 56.52174% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.67%. Comparing base (71596de) to head (f348629).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...software/os/windows/WindowsOperatingSystemFFM.java 53.84% 4 Missing and 2 partials ⚠️
...e/platform/windows/WindowsCentralProcessorFFM.java 50.00% 0 Missing and 3 partials ⚠️
.../oshi/software/os/windows/WindowsOSProcessFFM.java 66.66% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3290      +/-   ##
============================================
- Coverage     75.73%   75.67%   -0.06%     
  Complexity       76       76              
============================================
  Files           410      410              
  Lines         15817    15814       -3     
  Branches       2515     2518       +3     
============================================
- Hits          11979    11968      -11     
- Misses         2373     2379       +6     
- Partials       1465     1467       +2     
Flag Coverage Δ
linux 40.12% <0.00%> (+<0.01%) ⬆️
macos 40.94% <0.00%> (+0.01%) ⬆️
windows 48.67% <56.52%> (-0.07%) ⬇️

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

☔ View full report in Codecov by Sentry.
📢 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.

Introduce NativeHandle, a lightweight AutoCloseable wrapper around
native MemorySegment handles that ensures proper cleanup via
try-with-resources. This eliminates error-prone manual finally blocks
for native handle lifecycle management.

NativeHandle:
- Wraps a MemorySegment with a ThrowingCloser callback
- Skips close if handle is null or zero-address
- Logs and suppresses exceptions from the closer
- Fully tested with unit tests

Migrate simple single-handle Windows FFM methods as reference:
- WindowsFileSystemFFM.getLocalVolumes() (FindVolumeClose)
- WindowsCentralProcessorFFM registry methods (RegCloseKey)
- WindowsOperatingSystemFFM.enableDebugPrivilege() (CloseHandle)
- WindowsOperatingSystemFFM.queryServicesFFM() (CloseServiceHandle)
- WindowsOSProcessFFM.getAffinityMask() (CloseHandle)
@dbwiddis
dbwiddis force-pushed the add-native-handle-autocloseable branch from f403b28 to f348629 Compare May 23, 2026 21:18
@dbwiddis
dbwiddis merged commit 47e9f43 into oshi:master May 23, 2026
19 of 20 checks passed
@dbwiddis
dbwiddis deleted the add-native-handle-autocloseable branch May 23, 2026 21:25
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