Skip to content
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

Ensure delayed initialization of JsonArray/JsonObject is thread-safe #77567

Merged
merged 3 commits into from
Oct 28, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 @@ -5,6 +5,7 @@
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json.Serialization.Converters;
using System.Threading;

namespace System.Text.Json.Nodes
{
Expand Down Expand Up @@ -85,7 +86,7 @@ private void InitializeFromArray(JsonNode?[] items)
throw new InvalidOperationException(SR.Format(SR.NodeElementWrongType, nameof(JsonValueKind.Array)));
}

internal JsonArray (JsonElement element, JsonNodeOptions? options = null) : base(options)
internal JsonArray(JsonElement element, JsonNodeOptions? options = null) : base(options)
{
Debug.Assert(element.ValueKind == JsonValueKind.Array);
_jsonElement = element;
Expand Down Expand Up @@ -180,34 +181,41 @@ public override void WriteTo(Utf8JsonWriter writer, JsonSerializerOptions? optio

private void CreateNodes()
{
if (_list == null)
// Even though _list initialization can be subject to races,
// ensure that contending threads use a coherent view of jsonElement.

JsonElement? jsonElement = _jsonElement;
eiriktsarpalis marked this conversation as resolved.
Show resolved Hide resolved
Interlocked.MemoryBarrier();
List<JsonNode?>? list = _list;

if (list is null)
layomia marked this conversation as resolved.
Show resolved Hide resolved
{
List<JsonNode?> list;
_list = CreateNodesCore(jsonElement);
Interlocked.MemoryBarrier();
_jsonElement = null;
}
}

if (_jsonElement == null)
{
list = new List<JsonNode?>();
}
else
{
JsonElement jElement = _jsonElement.Value;
Debug.Assert(jElement.ValueKind == JsonValueKind.Array);
private List<JsonNode?> CreateNodesCore(JsonElement? jsonElement)
{
List<JsonNode?> list = new();

list = new List<JsonNode?>(jElement.GetArrayLength());
if (jsonElement.HasValue)
{
JsonElement jElement = jsonElement.Value;
Debug.Assert(jElement.ValueKind == JsonValueKind.Array);

foreach (JsonElement element in jElement.EnumerateArray())
{
JsonNode? node = JsonNodeConverter.Create(element, Options);
node?.AssignParent(this);
list.Add(node);
}
list = new List<JsonNode?>(jElement.GetArrayLength());

// Clear since no longer needed.
_jsonElement = null;
foreach (JsonElement element in jElement.EnumerateArray())
{
JsonNode? node = JsonNodeConverter.Create(element, Options);
node?.AssignParent(this);
list.Add(node);
}

_list = list;
}

return list;
}

[ExcludeFromCodeCoverage] // Justification = "Design-time"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.Json.Serialization.Converters;
using System.Threading;

namespace System.Text.Json.Nodes
{
Expand Down Expand Up @@ -261,18 +262,28 @@ IEnumerator IEnumerable.GetEnumerator()

private void InitializeIfRequired()
{
if (_dictionary != null)
// Even though _dictionary initialization can be subject to races,
// ensure that contending threads use a coherent view of jsonElement.

JsonElement? jsonElement = _jsonElement;
Interlocked.MemoryBarrier();
JsonPropertyDictionary<JsonNode?>? dictionary = _dictionary;

if (dictionary is null)
{
return;
_dictionary = InitializeIfRequiredCore(jsonElement);
Interlocked.MemoryBarrier();
_jsonElement = null;
}
}

private JsonPropertyDictionary<JsonNode?> InitializeIfRequiredCore(JsonElement? jsonElement)
eiriktsarpalis marked this conversation as resolved.
Show resolved Hide resolved
{
bool caseInsensitive = Options.HasValue ? Options.Value.PropertyNameCaseInsensitive : false;
var dictionary = new JsonPropertyDictionary<JsonNode?>(caseInsensitive);
if (_jsonElement.HasValue)
if (jsonElement.HasValue)
{
JsonElement jElement = _jsonElement.Value;

foreach (JsonProperty jElementProperty in jElement.EnumerateObject())
foreach (JsonProperty jElementProperty in jsonElement.Value.EnumerateObject())
{
JsonNode? node = JsonNodeConverter.Create(jElementProperty.Value, Options);
if (node != null)
Expand All @@ -282,11 +293,9 @@ private void InitializeIfRequired()

dictionary.Add(new KeyValuePair<string, JsonNode?>(jElementProperty.Name, node));
}

_jsonElement = null;
}

_dictionary = dictionary;
return dictionary;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Xunit;

namespace System.Text.Json.Nodes.Tests
Expand Down Expand Up @@ -473,5 +474,17 @@ public static void GetJsonArrayIEnumerable()
Assert.True(jArrayEnumerator.MoveNext());
Assert.Equal("value", ((JsonValue)jArrayEnumerator.Current).GetValue<string>());
}

[Fact]
public static void LazyInitializationIsThreadSafe()
{
string arrayText = "[\"elem0\",\"elem1\"]";
JsonArray node = Assert.IsType<JsonArray>(JsonNode.Parse(arrayText));
Parallel.For(0, 128, i =>
{
Assert.Equal("elem0", (string)node[0]);
Assert.Equal("elem1", (string)node[1]);
});
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.IO;
using System.Linq;
using System.Text.Json.Serialization.Tests;
using System.Threading.Tasks;
using Xunit;

namespace System.Text.Json.Nodes.Tests
Expand Down Expand Up @@ -956,5 +957,17 @@ static void Test(JsonObject jObject)
Assert.Equal("World", (string)jObject["hello"]); // Test case insensitivity
}
}

[Fact]
public static void LazyInitializationIsThreadSafe()
{
string arrayText = "{\"prop0\":0,\"prop1\":1}";
JsonObject jObj = Assert.IsType<JsonObject>(JsonNode.Parse(arrayText));
Parallel.For(0, 128, i =>
{
Assert.Equal(0, (int)jObj["prop0"]);
Assert.Equal(1, (int)jObj["prop1"]);
});
}
}
}