Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is returning an int an atomic operation in java?

// 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.

like image 933
cohadar Avatar asked Dec 02 '12 11:12

cohadar


1 Answers

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.

like image 162
Tomasz Nurkiewicz Avatar answered Nov 02 '22 04:11

Tomasz Nurkiewicz