Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit 9892c73

Browse files
committed
Fix race condition when writing to __uniqueTypes
1 parent 3b38c79 commit 9892c73

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

src/ServiceStack.Text/JsConfig.cs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
using System.Collections.Generic;
33
using System.IO;
44
using System.Reflection;
5+
using System.Threading;
56
using ServiceStack.Text.Common;
67
using ServiceStack.Text.Json;
78
using ServiceStack.Text.Jsv;
@@ -624,7 +625,24 @@ internal static void InvokeReset(this Type genericType)
624625
methodInfo.Invoke(null, null);
625626
}
626627

627-
internal static HashSet<Type> __uniqueTypes = new HashSet<Type>();
628+
internal static HashSet<Type> __uniqueTypes = new HashSet<Type>();
629+
internal static int __uniqueTypesCount = 0;
630+
631+
internal static void AddUniqueType(Type type)
632+
{
633+
if (__uniqueTypes.Contains(type))
634+
return;
635+
636+
HashSet<Type> newTypes, snapshot;
637+
do
638+
{
639+
snapshot = __uniqueTypes;
640+
newTypes = new HashSet<Type>(__uniqueTypes) { type };
641+
__uniqueTypesCount = newTypes.Count;
642+
643+
} while (!ReferenceEquals(
644+
Interlocked.CompareExchange(ref __uniqueTypes, newTypes, snapshot), snapshot));
645+
}
628646
}
629647

630648
public class JsConfig<T>

src/ServiceStack.Text/TypeConfig.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ internal void AssertValidUsage()
1616
{
1717
if (!IsUserType) return;
1818

19-
LicenseUtils.AssertValidUsage(LicenseFeature.Text, QuotaType.Types, JsConfig.__uniqueTypes.Count);
19+
LicenseUtils.AssertValidUsage(LicenseFeature.Text, QuotaType.Types, JsConfig.__uniqueTypesCount);
2020
}
2121

2222
internal TypeConfig(Type type)
@@ -26,7 +26,7 @@ internal TypeConfig(Type type)
2626
Properties = new PropertyInfo[0];
2727
Fields = new FieldInfo[0];
2828

29-
JsConfig.__uniqueTypes.Add(Type);
29+
JsConfig.AddUniqueType(Type);
3030
}
3131
}
3232

0 commit comments

Comments
 (0)