I have code that I want to execute with a single initialization. But this code does not have a specific life cycle, so my logic could potentially be called by multiple threads before my initialization. Therefore, I basically want to make sure that my logic code βwaitsβ until initialization is complete.
This is my first cut.
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(); } }
I basically want to make sure that this will do what I think it will happen - block doStuff while true is initialized, and that I will not miss the race conditions when doStuff can get stuck on the object. wait (), which will never appear.
Edit:
I have no control over the threads. And I want to be able to control when all initialization is done, so doStuff () cannot call initialise ().
I used AtomicBoolean, as it was a combination of the owner of the value, and an object that I could synchronize. I could also just have a "public static final object Lock = new Object ();" and a simple boolean flag. AtomicBoolean conveniently gave me both. Boolean value cannot be changed.
CountDownLatch is exactly what I was looking for. I also considered using Sempahore with 0 permissions. But CountDownLatch is perfect for this task.
source share