Skip to content

Conversation

@bitsandfoxes
Copy link
Contributor

@bitsandfoxes bitsandfoxes commented Nov 18, 2025

Resolves #2423

Problem

The SDK was experiencing SIGSEGV crashes in a native library when running on Android. It looked like the crashes occurred when native code attempted to use JNI on a background thread.

Root Cause

SentryJava previously used ThreadPool.QueueUserWorkItem to perform scope sync operations on non-main threads. Per Unity's JNI documentation, threads must be explicitly attached to and detached from the JVM to use JNI.

The previous approach (see in #2107 and #2215) was:

  1. Queue work to the ThreadPool
  2. Call AndroidJNI.AttachCurrentThread()
  3. Perform JNI operations
  4. Call AndroidJNI.DetachCurrentThread()

The Issue: In high-pressure environments, ThreadPool threads seem to get aggressively reused. When Sentry detached a ThreadPool thread after its operation, that same thread could be immediately reassigned to other code (e.g., Azure SDK) and that thread still expected JNI to be available. This caused:

  • Managed code (Unity's AndroidJavaObject) to fail with "field not found" errors (locally reproducible)
  • Native code to crash with SIGSEGV when dereferencing null JNI pointers

The SDK has no way to know if a ThreadPool thread is already attached by other code, making safe attach/detach impossible in a shared thread pool environment.

Solution

Replace the ThreadPool-based approach with a dedicated worker thread that the SDK fully controls:

  • Lifecycle Management: Worker thread is created in SentryJava constructor and disposed in Close()
  • Single Attach/Detach: Thread attaches to JNI once on creation, detaches once on shutdown
  • Work Queue: Uses ConcurrentQueue<(Action, string)> with AutoResetEvent for work dispatch

@bitsandfoxes bitsandfoxes changed the base branch from main to feat/bump-net-6 November 18, 2025 15:13
@bitsandfoxes bitsandfoxes requested a review from a team November 19, 2025 09:49
@bitsandfoxes bitsandfoxes marked this pull request as ready for review November 19, 2025 09:49
@bitsandfoxes bitsandfoxes merged commit 977c4f5 into feat/bump-net-6 Nov 19, 2025
16 checks passed
@bitsandfoxes bitsandfoxes deleted the fix/replace-android-async-scope-sync branch November 19, 2025 11:15
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.

3 participants