Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is java.util.concurrent.CountDownLatch.countDown() atomic?

I need reassurance that java.util.concurrent.CountDownLatch.countDown() is atomic.

I'm calling countDown in finally blocks so I'm confident that I'm using it correctly. Occasionally though I see one or two outstanding latches despite my thinking there should be none.

(I haven't managed to verify by checking the Java source code.)

like image 676
Bathsheba Avatar asked Sep 19 '25 02:09

Bathsheba


1 Answers

I need reassurance that java.util.concurrent.CountDownLatch.countDown() is atomic.

I reassure you, it most definitely is atomic. It would be a critical bug if it was not. I expect you will find your code problem if you debug your code.

(I haven't managed to verify by checking the Java source code.)

Here's the code trace:

public void countDown() {
    sync.releaseShared(1);
}

Default implementation of sync is:

    public boolean tryReleaseShared(int releases) {
        // Decrement count; signal when transition to zero
        for (;;) {
            int c = getState();
            if (c == 0)
                return false;
            int nextc = c-1;
            if (compareAndSetState(c, nextc))
                return nextc == 0;
        }
    }

compareAndSetState calls which uses the same Unsafe class that backs the AtomicInteger and many other classes.

return unsafe.compareAndSwapInt(this, stateOffset, expect, update);

If it was broken then a large portion of the java.util.concurrent are broken.

like image 79
Gray Avatar answered Sep 20 '25 17:09

Gray