[TrimmableTypeMap] Fix thread safety in TrimmableTypeMap.Initialize#11049
[TrimmableTypeMap] Fix thread safety in TrimmableTypeMap.Initialize#11049
Conversation
|
@copilot try again |
Agent-Logs-Url: https://github.com/dotnet/android/sessions/cb7028a6-408a-410f-9e71-a8d53aa9c2ec Co-authored-by: simonrozsival <374616+simonrozsival@users.noreply.github.com>
|
@copilot continue |
There was a problem hiding this comment.
Pull request overview
Adjusts TrimmableTypeMap.Initialize() in Mono.Android to avoid redundant JNI native registration work when multiple threads race to initialize the singleton, supporting the Trimmable Type Map runtime path.
Changes:
- Add an early-return guard after
Interlocked.CompareExchangeso only the winning initializer registers JNI natives. - Remove the prior debug-only “must only be created once” assertion behavior.
| internal static void Initialize () | ||
| { | ||
| var instance = new TrimmableTypeMap (); | ||
| var previous = Interlocked.CompareExchange (ref s_instance, instance, null); | ||
| Debug.Assert (previous is null, "TrimmableTypeMap must only be created once."); | ||
| if (previous is not null) | ||
| return; |
There was a problem hiding this comment.
Debug.Assert was removed, so using System.Diagnostics; in this file is now unused. Please remove the unused using to avoid analyzer/warning failures in builds that treat warnings as errors.
| internal static void Initialize () | ||
| { | ||
| var instance = new TrimmableTypeMap (); | ||
| var previous = Interlocked.CompareExchange (ref s_instance, instance, null); | ||
| Debug.Assert (previous is null, "TrimmableTypeMap must only be created once."); | ||
| if (previous is not null) | ||
| return; | ||
|
|
||
| instance.RegisterNatives (); | ||
| } |
There was a problem hiding this comment.
With the early-return, a concurrent caller can return from Initialize() while the winning thread is still in the middle of instance.RegisterNatives(). Since the method’s contract is “initialize and register natives”, consider ensuring other threads either wait for registration to complete (e.g., via Lazy/LazyInitializer or an init-state gate) or only publish s_instance after native registration has succeeded.
|
@copilot address the review comments. Use a static |
Agent-Logs-Url: https://github.com/dotnet/android/sessions/fa7fcbcb-4960-4629-a4a2-627b90a610ec Co-authored-by: simonrozsival <374616+simonrozsival@users.noreply.github.com>
Done in 5a8136b. The implementation now uses a static |
Thanks for asking me to work on this. I will get started on it and keep this PR's description up to date as I form a plan and make progress.