// 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
intare 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 ofint.Using
lockinArrayBlockingQueuemight be due to visibility reasons.countvariable is notvolatileso if the queue was modified in the meantime, without some sort of locking you are not guaranteed to see the most recent value ofcount. 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.