Note that there are some explanatory texts on larger screens.

plurals
  1. POCan I get rid of this read lock?
    primarykey
    data
    text
    <p>I have the following helper class (simplified):</p> <pre><code>public static class Cache { private static readonly object _syncRoot = new object(); private static Dictionary&lt;Type, string&gt; _lookup = new Dictionary&lt;Type, string&gt;(); public static void Add(Type type, string value) { lock (_syncRoot) { _lookup.Add(type, value); } } public static string Lookup(Type type) { string result; lock (_syncRoot) { _lookup.TryGetValue(type, out result); } return result; } } </code></pre> <p><code>Add</code> will be called roughly 10/100 times in the application and <code>Lookup</code> will be called by many threads, many of thousands of times. What I would like is to get rid of the read lock.</p> <p><strong>How do you normally get rid of the read lock in this situation?</strong></p> <p>I have the following ideas:</p> <ol> <li><p><em>Require that <code>_lookup</code> is stable before the application starts operation.</em> The could be build up from an <code>Attribute</code>. This is done automatically through the static constructor the attribute is assigned to. Requiring the above would require me to go through all types that could have the attribute and calling <code>RuntimeHelpers.RunClassConstructor</code> which is an expensive operation;</p></li> <li><p><em>Move to <a href="http://en.wikipedia.org/wiki/Copy-on-write" rel="nofollow noreferrer">COW</a> semantics.</em></p> <pre><code>public static void Add(Type type, string value) { lock (_syncRoot) { var lookup = new Dictionary&lt;Type, string&gt;(_lookup); lookup.Add(type, value); _lookup = lookup; } } </code></pre> <p>(With the <code>lock (_syncRoot)</code> removed in the <code>Lookup</code> method.) The problem with this is that this uses an unnecessary amount of memory (which might not be a problem) and I would probably make <code>_lookup</code> volatile, but I'm not sure how this should be applied. (<a href="https://stackoverflow.com/questions/1378490/read-write-locking-a-static-var-in-asp-net/1378513#1378513">John Skeets' comment here gives me pause.</a>)</p></li> <li><em>Using <code>ReaderWriterLock</code>.</em> I believe this would make things worse since the region being locked is small.</li> </ol> <p>Suggestions are very welcome.</p> <p><strong>UPDATE:</strong></p> <p>The values of the cache are immutable.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload