Is this implementation correct and thread safe, and is it even possible to use Atomic Variables for thread synchronization and control?
Yes, but for the readyCounter variable readyCounter you should probably use a CountDownLatch , for example:
private static AtomicInteger initCounter = new AtomicInteger(); private static CountDownLatch readyCounter = new CountDownLatch(1); static Object getInstance() { if (initCounter.incrementAndGet() == 1) { try { instance = new Object(); return instance; } finally { readyCounter.countDown(); } } else { readyCounter.await(); return instance; } }
Calling waitait () also resolves the initialization race condition. (I also added a try-finally block to avoid deadlocks in the constructor exception.)
Additional question: if this implementation is thread safe, do I really need a mutable modifier for the instance variable?
Not unless you call the appropriate AtomicInteger or CountDownLatch before accessing the instance variable. See what happened earlier in the documentation .
source share