Note that there are some explanatory texts on larger screens.

plurals
  1. POName for this pattern? (Answer: lazy initialization with double-checked locking)
    primarykey
    data
    text
    <p>Consider the following code:</p> <pre><code>public class Foo { private static object _lock = new object(); public void NameDoesNotMatter() { if( SomeDataDoesNotExist() ) { lock(_lock) { if( SomeDataDoesNotExist() ) { CreateSomeData(); } else { // someone else also noticed the lack of data. We // both contended for the lock. The other guy won // and created the data, so we no longer need to. // But once he got out of the lock, we got in. // There's nothing left to do. } } } } private bool SomeDataDoesNotExist() { // Note - this method must be thread-safe. throw new NotImplementedException(); } private bool CreateSomeData() { // Note - This shouldn't need to be thread-safe throw new NotImplementedException(); } } </code></pre> <p>First, there are some assumptions I need to state:</p> <ol> <li><p>There is a good reason I couldn't just do this once an app startup. Maybe the data wasn't available yet, etc.</p></li> <li><p>Foo may be instantiated and used concurrently from two or more threads. I want one of them to end up creating some data (but not both of them) then I'll allow both to access that same data (ignore thread safety of accessing the data)</p></li> <li><p>The cost to SomeDataDoesNotExist() is not huge.</p></li> </ol> <p>Now, this doesn't necessarily have to be confined to some data creation situation, but this was an example I could think of.</p> <p>The part that I'm especially interested in identifying as a pattern is the check -> lock -> check. I've had to explain this pattern to developers on a few occasions who didn't get the algorithm at first glance but could then appreciate it.</p> <p>Anyway, other people must do similarly. Is this a standardized pattern? What's it called?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    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