title: How to freeze a popsicle in .NET (make a class immutable)
body: <p>I'm designing a class that I wish to make readonly after a main thread is done configuring it, i.e. "freeze" it. Eric Lippert calls this <a href="http://blogs.msdn.com/b/ericlippert/archive/2011/05/23/read-only-and-threadsafe-are-different.aspx">popsicle</a> immutability. After it is frozen, it can be accessed by multiple threads concurrently for reading.</p>
  
  <p>My question is how to write this in a thread safe way that is <em>realistically</em> efficient, i.e. without trying to be unnecessarily <em>clever</em>.</p>
  
  <p><strong>Attempt 1:</strong></p>
  
  <pre><code>public class Foobar
  {
     private Boolean _isFrozen;
  
     public void Freeze() { _isFrozen = true; }
  
     // Only intended to be called by main thread, so checks if class is frozen. If it is the operation is invalid.
     public void WriteValue(Object val)
     {
        if (_isFrozen)
           throw new InvalidOperationException();
  
        // write ...
     }
  
     public Object ReadSomething()
     {
        return it;
     }
  }
  </code></pre>
  
  <p>Eric Lippert seems to suggest this would be OK in <a href="http://blogs.msdn.com/b/ericlippert/archive/2011/05/23/read-only-and-threadsafe-are-different.aspx">this</a> post.
  I know writes have release semantics, but as far as I understand this only pertains to <em>ordering</em>, and it doesn't necessarily mean that all threads will see the value immediately after the write. Can anyone confirm this? This would mean this solution is not thread safe (this may not be the only reason of course).</p>
  
  <p><strong>Attempt 2:</strong></p>
  
  <p>The above, but using <code>Interlocked.Exchange</code> to ensure the value is actually published:</p>
  
  <pre><code>public class Foobar
  {
     private Int32 _isFrozen;
  
     public void Freeze() { Interlocked.Exchange(ref _isFrozen, 1); }
  
     public void WriteValue(Object val)
     {
        if (_isFrozen == 1)
           throw new InvalidOperationException();
  
        // write ...
     }
  }
  </code></pre>
  
  <p>Advantage here would be that we ensure the value is published without suffering the overhead on every read. If none of the reads are moved before the write to _isFrozen as the Interlocked method uses a full memory barrier I would guess this is thread safe. However, who knows what the compiler will do (and according to section 3.10 of the C# spec that seems like quite a lot), so I don't know if this is threadsafe.</p>
  
  <p><strong>Attempt 3:</strong></p>
  
  <p>Also do the read using <code>Interlocked</code>.</p>
  
  <pre><code>public class Foobar
  {
     private Int32 _isFrozen;
  
     public void Freeze() { Interlocked.Exchange(ref _isFrozen, 1); }
  
     public void WriteValue(Object val)
     {
        if (Interlocked.CompareExchange(ref _isFrozen, 0, 0) == 1)
           throw new InvalidOperationException();
  
        // write ...
     }
  }
  </code></pre>
  
  <p>Definitely thread safe, but it seems a little wasteful to have to do the compare exchange for every read. I know this overhead is probably minimal, but I'm looking for a <em>reasonably</em> efficient method (although perhaps this is it).</p>
  
  <p><strong>Attempt 4:</strong></p>
  
  <p>Using <code>volatile</code>:</p>
  
  <pre><code>public class Foobar
  {
     private volatile Boolean _isFrozen;
  
     public void Freeze() { _isFrozen = true; }
  
     public void WriteValue(Object val)
     {
        if (_isFrozen)
           throw new InvalidOperationException();
  
        // write ...
     }
  }
  </code></pre>
  
  <p>But Joe Duffy declared "<a href="http://www.bluebytesoftware.com/blog/2010/12/04/SayonaraVolatile.aspx">sayonara volatile</a>", so I won't consider this a solution.</p>
  
  <p><strong>Attempt 5:</strong></p>
  
  <p>Lock everything, seems a bit overkill:</p>
  
  <pre><code>public class Foobar
  {
     private readonly Object _syncRoot = new Object();
     private Boolean _isFrozen;
  
     public void Freeze() { lock(_syncRoot) _isFrozen = true; }
  
     public void WriteValue(Object val)
     {
        lock(_syncRoot) // as above we could include an attempt that reads *without* this lock
           if (_isFrozen)
              throw new InvalidOperationException();
  
        // write ...
     }
  }
  </code></pre>
  
  <p>Also seems definitely thread safe, but has more overhead than using the Interlocked approach above, so I would favour attempt 3 over this one.</p>
  
  <p>And then I can come up with at least some more (I'm sure there are many more):</p>
  
  <p><strong>Attempt 6:</strong> use <code>Thread.VolatileWrite</code> and <code>Thread.VolatileRead</code>, but these are supposedly a little on the heavy side.</p>
  
  <p><strong>Attempt 7:</strong> use <code>Thread.MemoryBarrier</code>, seems a little too <em>internal</em>.</p>
  
  <p><strong>Attempt 8:</strong> create an immutable copy - don't want to do this</p>
  
  <p>Summarising:</p>
  
  <ul>
  <li>which attempt would you use and why (or how would you do it if entirely different)? (i.e. what is the best way for publishing a value once that is then read concurrently, while being reasonably efficient without being overly "clever"?)</li>
  <li>does .NET's memory model "release" semantics of writes imply that all other threads see updates (cache coherency etc.)? I generally don't want to think too much about this, but it's nice to have an understanding.</li>
  </ul>
  
  <p>EDIT:</p>
  
  <p>Perhaps my question wasn't clear, but I am looking in particular for reasons as to why the above attempts are good or bad. Note that I am talking here about a scenario of one single writer that writes then freezes before any concurrent reads. I believe attempt 1 is OK but I'd like to know exactly why (as I wonder if reads could be optimized away somehow, for example).
  I care less about whether or not this is good design practice but more about the actual threading aspect of it.</p>
  
  <hr>
  
  <p>Many thanks for the response the question received, but I have chosen to mark this as an answer myself because I feel that the answers given do not <em>quite</em> answer my question and I do not want to give the impression to anyone visiting the site that the marked answer is correct simply because it was automatically marked as such due to the bounty expiring.
  Furthermore I do not think the answer with the highest number of votes was overwhelmingly voted for, not enough to mark it automatically as an answer.</p>
  
  <p>I am still leaning to attempt #1 being correct, however, I would have liked some authoritative answers. I understand x86 has a strong model, but I don't want to (and shouldn't) code for a particular architecture, after all that's one of the nice things about .NET.</p>
  
  <p>If you are in doubt about the answer, go for one of the locking approaches, perhaps with the optimizations shown here to avoid a lot of contention on the lock.</p>