Skip to content

Commit

Permalink
ICU4N.Impl.Locale.LocaleObjectCache: Made parameter of LurchTable int…
Browse files Browse the repository at this point in the history
…o a Lazy<T> to ensure two threads cannot load the cache at the same time. (fixes #31)
  • Loading branch information
NightOwl888 committed Mar 9, 2021
1 parent 4de1909 commit a417830
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/ICU4N/Impl/Locale/LocaleObjectCache.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
using J2N.Collections.Concurrent;
using System;

namespace ICU4N.Impl.Locale
{
public abstract class LocaleObjectCache<TKey, TValue> where TValue : class
{
private readonly LurchTable<TKey, TValue> _map;
private readonly LurchTable<TKey, Lazy<TValue>> _map;

public LocaleObjectCache()
: this(16)
Expand All @@ -16,12 +17,13 @@ public LocaleObjectCache(int initialCapacity)
// ICU4N: Since .NET doesn't have a memory-sensitive cache, we are using an LRU cache with a fixed size.
// This ensures that the culture(s) that the application uses most stay near the top of the cache and
// less used cultures get popped off of the bottom of the cache.
_map = new LurchTable<TKey, TValue>(initialCapacity, LurchTableOrder.Access, limit: 64, comparer: null);
_map = new LurchTable<TKey, Lazy<TValue>>(initialCapacity, LurchTableOrder.Access, limit: 64, comparer: null);
}

public virtual TValue Get(TKey key)
{
return _map.GetOrAdd(key, CreateObject);
var result = _map.GetOrAdd(key, (key) => new Lazy<TValue>(() => CreateObject(key)));
return result.Value;
}

protected abstract TValue CreateObject(TKey key);
Expand Down

0 comments on commit a417830

Please sign in to comment.