I want to know if calculation of the function value and assignment of the result to a variable is an atomic operation in Java.
For example:
I have a thread-safe priority queue q. In q I save elements, and each element has a rank according to which it is placed in the queue. In addition I have a shared variable topRank that should always contain the rank of the topmost element in q. The following code is executed in parallel by number of threads:
element = q.remove(); // do something with element
topRank = q.peek();
could it happen that threadA would remove one elements from q and calculate value of q.peek() and just before assigning it to topRank would be interrupted by threadB, then threadB would remove one more element from q and update topRank. And then threadA would resume to assignment of incorrect value to the topRank.
A link to official literature would be very appreciated.
Thanks.
The short answer is that these operations are NOT atomic and you need to write the synchronization into your code. This is a HUGE topic and there is a lot to learn about writing thread-safe programs. Google for “java thread safety” and “java multithreading”.