I am trying to understand how atomic operations work, particularly in Java.
Take AtomicInteger
. The document says it is: "An int value that may be updated atomically." For example, one of the operations which is atomic for this class is:
/**
* Atomically sets to the given value and returns the old value.
*
* @param newValue the new value
* @return the previous value
*/
public final int getAndSet(int newValue) {
return unsafe.getAndSetInt(this, valueOffset, newValue);
}
As per documentation, it is guaranteed that this would be an atomic operation. However, the actual method unsafe.getAndSetInt()
would have at least a few lines to execute. How then is atomicity guaranteed?
For example, if Thread-A is currently executing this code, why can't this be preempted? As I understand it is OS's scheduler which will share the timeslice among other threads, how it gets decided if a Thread is executing some atomic method, then all instructions need to get executed.
Is this arrangement done at the OS level? Is there a contract between JVM, API Call, and OS that if a Thread executing someFoo() method (assuming atomic), then it is atomic, and needs to be completed by that Thread and without being preempted?