Note that there are some explanatory texts on larger screens.

plurals
  1. POControlling race condition at startup
    primarykey
    data
    text
    <p>I have some code that I want to have some one time initialisation performed. But this code doesn't have a definite lifecycle, so my logic can be potentially invoked by multiple threads before my initialisation is done. So, I want to basically ensure that my logic code "waits" until initialisation is done.</p> <p>This is my first cut.</p> <pre><code>public class MyClass { private static final AtomicBoolean initialised = new AtomicBoolean(false); public void initialise() { synchronized(initialised) { initStuff(); initialised.getAndSet(true); initialised.notifyAll(); } } public void doStuff() { synchronized(initialised) { if (!initialised.get()) { try { initialised.wait(); } catch (InterruptedException ex) { throw new RuntimeException("Uh oh!", ex); } } } doOtherStuff(); } } </code></pre> <p>I basically want to make sure this is going to do what I think it's going to do -- block doStuff until the initialised is true, and that I'm not missing a race condition where doStuff might get stuck on a Object.wait() that will never arrive.</p> <p>Edit:</p> <p>I have no control over the threads. And I want to be able to control when all of the initialisation is done, which is why doStuff() can't call initialise().</p> <p>I used an AtomicBoolean as it was a combination of a value holder, and an object I could synchronize. I could have also simply had a "public static final Object lock = new Object();" and a simple boolean flag. AtomicBoolean conveniently gave me both. A Boolean can not be modified.</p> <p>The CountDownLatch is exactly what I was looking for. I also considered using a Sempahore with 0 permits. But the CountDownLatch is perfect for just this task.</p>
    singulars
    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