Repository navigation
[Java.Interop] Keep peers alive across array, Equals, and ref calls - #13765
Conversation
Context: #13758 Relates to #13759 On CoreCLR and NativeAOT, optimized builds track managed object liveness per instruction rather than to method or lexical-scope end. Once a JNI handle is read from PeerReference into a value type, the GC bridge can convert the peer's global reference to a weak global reference and delete the old global reference before JNI finishes using the copied handle. Retain the managed peer across the remaining Bucket A Java.Interop JNI calls (item #1 FinishCreateInstance is already covered by #13758): * Retain the owning Java<T>Array on Jni<T>ArrayElements across all 8 primitive array types, keep the owner alive in Synchronize via finally, clear it on non-Commit release, and update the constructor <safety> contract (fixes GetElements, IndexOf, and Clear). * Add GC.KeepAlive (this) to Java<T>Array.CopyTo and CopyFrom, JavaArray<T>.Length, and JavaObjectArray<T>.GetElementAt, SetElementAt, and Clear. * Add GC.KeepAlive (this) and GC.KeepAlive (o) after JniEnvironment.Types.IsSameObject in JavaObject.Equals and JavaException.Equals. * Read value.PeerReference once and call GC.KeepAlive (value) in JniEnvironment.References.NewReturnToJniRef (IJavaPeerable). * Add JniArrayElementsTests.GetElements_RetainsOwnerUntilReleased to verify JniInt32ArrayElements roots its owning JavaInt32Array across GC bridge rounds and CopyToJava (Commit), then allows collection after Dispose. Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
After Release(Commit), the cleared elements pointer makes Dispose() a no-op while the owner reference remains set, keeping the Java array alive; this needs a fix and regression coverage.
1 open issue
What changed in this PR
This PR continues the peer-lifetime fixes tracked in #13759, following #13758. It keeps managed Java peers reachable while JNI uses their handles, addressing premature collection in optimized CoreCLR and NativeAOT builds.
Changes:
- Retain primitive-array owners until final release across all eight generated array types.
- Add lifetime protection to array operations, identity comparisons, and return-to-JNI reference creation.
- Add a regression test covering owner retention through Commit and collection after disposal.
| File | Description |
|---|---|
tests/Mono.Android-Tests/Java.Interop-Tests/Java.Interop/JavaInt32ArrayContractTests.cs |
Tests array-owner retention and collection after disposal. |
src/Java.Interop/Java.Interop/JniEnvironment.References.cs |
Reads the peer reference once and retains its owner during conversion. |
src/Java.Interop/Java.Interop/JavaPrimitiveArrays.tt |
Updates the template with owner retention and copy-operation lifetime protection. |
src/Java.Interop/Java.Interop/JavaPrimitiveArrays.cs |
Applies the template changes to all eight primitive types. |
src/Java.Interop/Java.Interop/JavaObjectArray.cs |
Retains the array during element reads, writes, and clearing. |
src/Java.Interop/Java.Interop/JavaObject.cs |
Retains both peers during JNI identity comparison. |
src/Java.Interop/Java.Interop/JavaException.cs |
Applies the same lifetime protection to exception equality. |
src/Java.Interop/Java.Interop/JavaArray.cs |
Retains the array while querying its length. |
Review effort: Balanced
Move the owning IJavaPeerable field onto the JniArrayElements base class so CopyToJava and Release share a single KeepAlive implementation and Release always clears owner (including Release(Commit)) after Synchronize succeeds. Make the constructor owner parameter non-nullable with ThrowIfNull, compute GetArrayLength before Get<T>ArrayElements in GetElements to avoid leaking the acquired buffer on throw, and use straight-line GC.KeepAlive (this) in JavaObjectArray<T>.Clear. Co-authored-by: Copilot App <[email protected]>
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
⚠️ Needs Changes
Findings: 0 errors · 1 warning · 0 suggestions. The inline warning requests focused regression coverage for the new array-owner retention guarantee; I found no additional correctness defect introduced by this diff.
Reviewed all seven changed files in full, the primitive-array template and generated implementations, relevant callers, project configuration, GC-bridge reference conversion, existing lifetime tests, and the resolved review thread. The changes consistently retain both operands for equality checks, retain wrappers across raw-handle JNI calls, and move the length query before buffer acquisition. Centralizing ownership in JniArrayElements covers all eight primitive types, with matching template updates and exception-safe retention during synchronization. The previously reported retained-owner issue is addressed by clearing the owner after successful terminal release.
CI: All 38 checks returned for the current PR head report success, including the aggregate dotnet-android check for Azure build 1697961. The direct Azure build query failed because authentication is required, so I could not independently verify its timeline or non-gating device-test results. The PR reports successful local Release builds and CoreCLR/NativeAOT device runs; I did not rerun them in this review. Linked issues #13758/#13759 could not both be reconciled with their full issue context because the configured GitHub read tools do not expose issue reads; this assessment is scoped to the submitted diff and available PR context.
Generated by Android PR Reviewer for #13765 · copilot · gpt61 · 48.2 AIC · ⌖ 4.39 AIC · ⊞ 21K
Comment /review to run again
|
@dalexsoto review |
|
Reviewed as part of the #13759 Bucket A audit. I checked the full diff against the audit items and found the placements correct — no issues to raise:
|
dalexsoto
left a comment
There was a problem hiding this comment.
The JNI peer lifetime fixes consistently keep wrappers alive through native access, and JniArrayElements now retains and releases its owner with the elements lifetime. The primitive-array template and generated implementations agree for all eight types; the changed internal constructors have no other callers in the pinned friend assembly. No blocking issues found, including after checking the current target-branch integration.

Context: #13758
Relates to #13759
In optimized CoreCLR and NativeAOT builds, managed object liveness is tracked per instruction rather than to method or lexical-scope end. Once
PeerReferenceis copied into aJniObjectReferencevalue, nothing keeps the managed peer reachable; a GC bridge cycle (JavaMarshalGCBridge.TakeWeakGlobalReference) can convert and delete the peer's global reference before JNI finishes using the copied handle, leading to ART CheckJNIuse of deleted global referenceaborts.Retain the owning managed peers across the remaining Bucket A
Java.Interopcall sites from #13759 (Bucket A item #1,JniPeerMembers.JniInstanceMethods.FinishCreateInstance, is tracked in open PR #13758; Bucket A will be complete once both PRs land):IJavaPeerableon theJniArrayElementsbase class (non-nullable constructor parameter checked withArgumentNullException.ThrowIfNull), keep it alive inCopyToJavaandReleaseviafinally, clear it onceReleasesucceeds (includingRelease (Commit)), and update the constructor<safety>contracts inJavaArray.csandJavaPrimitiveArrays.tt/JavaPrimitiveArrays.cs. ComputeGetArrayLengthbeforeGet<T>ArrayElementsinJava<T>Array.GetElementsso a throwing length check cannot leak the acquired native buffer. This fixesGetElements,IndexOf, andClearacross all 8 primitive array types as well as externalGetElements ()callers.thisalive acrossGet<T>ArrayRegion/Set<T>ArrayRegioninJava<T>Array.CopyToandCopyFrom, acrossGetArrayLengthinJavaArray<T>.Length, and acrossGetObjectArrayElement/SetObjectArrayElementinJavaObjectArray<T>.GetElementAt,SetElementAt, andClear.thisandoalive acrossJniEnvironment.Types.IsSameObjectinJavaObject.Equals (object?)andJavaException.Equals (object?).value.PeerReferenceonce and keepvaluealive inJniEnvironment.References.NewReturnToJniRef (IJavaPeerable).No GC-timing or early-collection retention regression test is added, as such tests are inherently timing-sensitive/flaky.
Validation
dotnet build src/Java.Interop/Java.Interop.csproj -v minimaland-c Release: 0 compiler warnings, 0 errors.make leeroy CONFIGURATION=Release MSBUILD_ARGS='-m:4 -nr:false': succeeded../dotnet-local.sh build -t:Install -c Release -p:RuntimeIdentifier=android-arm64 -p:Device=emulator-5558 tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj+dotnet test --no-build): 1122 passed, 0 failed, 4 skipped.-p:PublishAot=true, confirmed NativeAOT viaNativeAotStartupOffsetMatchesDevicepassing): 1059 passed, 0 failed, 4 skipped.