Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 636
Bober02 Avatar asked Mar 14 '23 15:03

Bober02


1 Answers

According to the javadoc:

Until the count reaches zero, actions in a thread prior to calling countDown() happen-before actions following a successful return from a corresponding await() in another thread.

So you don't need extra synchronisation if you only call setA once. If you call it a second time, because the count will already be 0, you won't get the same guarantee.

If the expected use is to only call setA once you could throw an exception if it is called more than once to enforce that contract (although checking the count AND assigning a new value to a atomically may be tricky without additional synchronisation).

If you are happy that setA can be called more than once then you need additional synchronisation.

like image 187
assylias Avatar answered Mar 24 '23 02:03

assylias