Json.NET
Code Coverage Statistics for Source File

Newtonsoft.Json\Utilities\ThreadSafeStore.cs

Symbol Coverage: 91.67% (22 of 24)

Branch Coverage: 90.00% (9 of 10)

Cyclomatic Complexity Avg: 2.67 Max:3

Code Lines: 24


L V Source
1
using System;
2
using System.Collections.Generic;
3

  
4
namespace Newtonsoft.Json.Utilities
5
{
6
  internal class ThreadSafeStore<TKey, TValue>
7
  {
8
 5
    private readonly object _lock = new object();
9
    private Dictionary<TKey, TValue> _store;
10
    private readonly Func<TKey, TValue> _creator;
11

  
12
 5
    public ThreadSafeStore(Func<TKey, TValue> creator)
13
    {
14
 5
      if (creator == null)
15
 0
        throw new ArgumentNullException("creator");
16

  
17
 5
      _creator = creator;
18
 5
    }
19

  
20
    public TValue Get(TKey key)
21
    {
22
 8834
      if (_store == null)
23
 5
        return AddValue(key);
24

  
25
      TValue value;
26
 8829
      if (!_store.TryGetValue(key, out value))
27
 1760
        return AddValue(key);
28

  
29
 7069
      return value;
30
 8834
    }
31

  
32
    private TValue AddValue(TKey key)
33
    {
34
 1765
      TValue value = _creator(key);
35

  
36
 1765
      lock (_lock)
37
      {
38
 1765
        if (_store == null)
39
        {
40
 5
          _store = new Dictionary<TKey, TValue>();
41
 5
          _store[key] = value;
42
        }
43
        else
44
        {
45
          // double check locking
46
          TValue checkValue;
47
 1760
          if (_store.TryGetValue(key, out checkValue))
48
 0
            return checkValue;
49

  
50
 1760
          Dictionary<TKey, TValue> newStore = new Dictionary<TKey, TValue>(_store);
51
 1760
          newStore[key] = value;
52

  
53
 1760
          _store = newStore;
54
        }
55

  
56
 1765
        return value;
57
      }
58
 1765
    }
59
  }
60
}