Search code examples
javamultithreadingsynchronizationcountdownlatch

Countdownlatch and further synchronisation


Supposedly I have the following class definition, when one thread wants to set a for multiple (potentially) waiting threads:

public class A {
    private int a;
    private CountDownLatch gate;

    public A(int a) {
        a = 1;
        gate = new CountDownLatch(1);
    }

    public int getA() {
        latch.await();
        return a;
    }

    public void setA(int a) {
        this.a = a;
        gate.countDown();
    }
}

It seems to me that a needs to be volatile, but I am not sure… Could someone please share why, if at all, there needs to be an extra synchronization around getA, or a needs to be volatile?


Solution

  • Actually a doesn't need to be volatile because countDown() loades and stores into volatile state variable of AbstractQueuedSynchronizer which is used inside CountDownLatch. Volatile store triggers a memory-barrier (great in-depth article about Memory Barriers and etc in JSR-133). And according to the JMM all previous stores (to other variables) would be visible to other threads.
    assylias is right, it would be true only if you call setA() once, because you construct latch as new CountDownLatch(1).