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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With