-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Fix thread safety issue in JsonObject.InitializeDictionary causing GetPath failures #120619
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis |
…rlocked.CompareExchange Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.IDictionary.cs
Outdated
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull Request Overview
This PR fixes a thread safety issue in JsonObject.InitializeDictionary()
that was causing GetPath()
calls to fail with InvalidOperationException
when multiple threads accessed the same JsonObject
concurrently.
Key changes:
- Replaced direct assignment with atomic
Interlocked.CompareExchange
to ensure only one dictionary instance is published - Added comprehensive thread safety test with 20 iterations of 100 parallel tasks
- Preserved existing memory barrier logic for proper ordering guarantees
Reviewed Changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.
File | Description |
---|---|
JsonObject.IDictionary.cs | Fixed race condition in dictionary initialization using atomic compare-exchange pattern |
JsonObjectTests.cs | Added thread safety test to validate concurrent GetPath() calls don't fail |
… already a full barrier Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.IDictionary.cs
Show resolved
Hide resolved
…Object.IDictionary.cs
Summary
Fixed thread safety issue in
JsonObject.InitializeDictionary()
where concurrent access could create multiple dictionary instances with different JsonNode objects, causingFindValue()
to fail withInvalidOperationException
when looking up child nodes by reference equality.The fix uses
Interlocked.CompareExchange
to atomically ensure only one dictionary instance is published to the_dictionary
field. Threads that lose the race use the already-published dictionary instead of their local copy, ensuring all threads see consistent JsonNode references.Test coverage includes new
GetPath_IsThreadSafe()
test that validates concurrent calls toGetPath()
on child nodes.Original prompt
Fixes #120617
✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.