Skip to content

Commit

Permalink
Merge pull request #672 from antonioaversa/string-intern-dict-concurr…
Browse files Browse the repository at this point in the history
…ency

Fix race condition in StringCache
  • Loading branch information
KirillOsenkov authored Apr 19, 2023
2 parents 0ab53ca + 9e59073 commit 4c16983
Showing 1 changed file with 5 additions and 17 deletions.
22 changes: 5 additions & 17 deletions src/StructuredLogger/Serialization/StringCache.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Collections.Generic;

namespace Microsoft.Build.Logging.StructuredLogger
{
public class StringCache
{
private Dictionary<string, string> deduplicationMap = new Dictionary<string, string>();
private ConcurrentDictionary<string, string> deduplicationMap = new ConcurrentDictionary<string, string>();

public IEnumerable<string> Instances { get; set; }

Expand Down Expand Up @@ -59,25 +60,12 @@ public string Intern(string text)
text = text.NormalizeLineBreaks();
}

lock (deduplicationMap)
{
if (deduplicationMap.TryGetValue(text, out string existing))
{
return existing;
}

deduplicationMap[text] = text;
}

return text;
return deduplicationMap.GetOrAdd(text, text);
}

public bool Contains(string text)
{
lock (deduplicationMap)
{
return deduplicationMap.ContainsKey(text);
}
return deduplicationMap.ContainsKey(text);
}

public IDictionary<string, string> InternStringDictionary(IDictionary<string, string> inputDictionary)
Expand Down

0 comments on commit 4c16983

Please sign in to comment.