Thread safe lazy initializer; is swapping Func<>s a good idea? <p>The class at the bottom is an implementation of fast, thread safe, "lock free", lazy initializer.</p> <p>I say "lock free", although it isn't completely; It uses a lock until it is initialized, and then replaces the call to get the data with one that doesn't use the lock. (Similar to a double checked lock with a volatile member; and from performance tests I get v. similar results.)</p> <p>My question is; is this a good/safe thing to do?</p> <p>(After I had written this I noticed that the .net 4.0 has a <code>LazyInit&lt;T&gt;</code> which performs the same operations and more, but in a very highly contrived example that I created my implementation was slightly faster :-) )</p> <p><strong>NB</strong> Class has been modified to include <code>Value</code> member, and volatile on the <code>_get</code></p> <pre><code>class ThreadSafeInitializer&lt;TOutput&gt; where TOutput : class { readonly object _sync = new object(); TOutput _output; private volatile Func&lt;TOutput&gt; _get; public TOutput Value { get { return _get(); } } public ThreadSafeInitializer(Func&lt;TOutput&gt; create) { _get = () =&gt; { lock (_sync) { if (_output == null) { _output = create(); _get = () =&gt; _output; // replace the Get method, so no longer need to lock } return _output; } }; } } </code></pre>