Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ public bool Remove(string propertyName)

if (dictionary is null)
{
dictionary = CreateDictionary(Options);
OrderedDictionary<string, JsonNode?> newDictionary = CreateDictionary(Options);

if (jsonElement.HasValue)
{
Expand All @@ -259,14 +259,24 @@ public bool Remove(string propertyName)
JsonNode? node = JsonNodeConverter.Create(jElementProperty.Value, Options);
node?.Parent = this;

dictionary.Add(jElementProperty.Name, node);
newDictionary.Add(jElementProperty.Name, node);
}
}

// Ensure _jsonElement is written to after _dictionary
_dictionary = dictionary;
Interlocked.MemoryBarrier();
_jsonElement = null;
// Ensure only one dictionary instance is published using CompareExchange
OrderedDictionary<string, JsonNode?>? exchangedDictionary = Interlocked.CompareExchange(ref _dictionary, newDictionary, null);
if (exchangedDictionary is null)
{
// We won the race and published our dictionary
// Ensure _jsonElement is written to after _dictionary
_jsonElement = null;
dictionary = newDictionary;
}
else
{
// Another thread won the race, use their dictionary
dictionary = exchangedDictionary;
}
}

return dictionary;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1789,5 +1789,26 @@ public static void Deserialize_WrongType(string json)
{
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<JsonObject>(json));
}

[Fact]
public static void GetPath_IsThreadSafe()
{
for (int attempt = 0; attempt < 20; attempt++)
{
var tree = (JsonNode.Parse(
"""
{
"oh": "noes"
}
"""
) as JsonObject)!;

Parallel.ForEach(Enumerable.Range(0, 100), new ParallelOptions { MaxDegreeOfParallelism = 16 }, _ =>
{
string path = tree.First().Value!.GetPath();
Assert.Equal("$.oh", path);
});
}
}
}
}
Loading