// is this atomic?
public int size() {
return count;
}
Note that count can be changed by other methods in other threads.
I know integer reads and writes are atomic, but I am not sure about return.
What got me alarmed is that for some reason ArrayBlockingQueue locks it's size() method.
Reads and writes to primitive int
are atomic as you already know. Returning is basically reading and placing in some other place in memory. Since reading is atomic, no race condition will occur. You either return previous or next value of int
.
Using lock
in ArrayBlockingQueue
might be due to visibility reasons. count
variable is not volatile
so if the queue was modified in the meantime, without some sort of locking you are not guaranteed to see the most recent value of count
. But since read and writes are atomic, at least you'll never see youngest 16 bits of old value and oldest 16 bits of new value.
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