Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Volatile can be a performance option in some cases to avoid the additional hit of using a lock, but it doesn't address threadsafety issues of race conditions, which your third example (the one at question) has.</p> <p>To make sure an uninitialized instance is not retrieved by another thread you should not assign to the static variable until you have a completely initialized instance. Then as soon as they see a non-null, they know it's good. <strong>Edited</strong>: (correction) While I think it's more ideal to avoid redundant work (below), I guess allowing regeneration and replacement of the static reference (as you had it, or Guffa's version) is still "safe" for your use case because each reference to <code>GetMyObject()</code> will grab the single object in place at the time.</p> <p>I would suggest something like this:</p> <pre><code>private static object s_Lock = new object(); private static volatile MyObject s_MyObject; private static MyObject LoadMyObject() { MyObject myObject = new MyObject(); myObject.Initialize(); return myObject; } public static MyObject GetMyObject() { if (s_MyObject == null) { lock (s_Lock) { if (s_MyObject == null) // Check again now that we're in the lock. s_MyObject = LoadMyObject(); // Only one access does this work. } } return s_MyObject; // Once it's set, it's never cleared or assigned again. } </code></pre> <p>This has the advantage of only doing the init work once, but also avoiding the lock contention overhead unless it's actually needed... while still being threadsafe. (You could use volatile as above if you want to be sure it propagates out, but this should also "work" without it; it would just be more likley to need the lock before seeing the new contents of <code>s_MyObject</code>, depending on the architecture. So I think volatile is helpful for this approach.)</p> <p>I've kept your <code>LoadMyObject</code> and <code>GetMyObject</code> methods, but you could also combine the logic into the then clause of the inner if for a single factory method.</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.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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