Skip to main content

Atomic Variables

why the word atomic?

Atomic in general means, something that can't be further divided. In case of Java, atomic variables does two tasks always as one atomic task.

Two tasks include get and set, compare and increment, etc.

In Java, Atomic variables refer to the variables which can be only accessed by one thread at a time. But this has no concept of lock. here.

Achieved using a special CPU instruction

CPU provides this feature of serializing access to a memory address via a special instruction. Java simply uses it to achieve this.

CAS - Compare and Save

Compare and Save is just one of the features of atomic variables.

Since atomic variables only ensure atomicity just for that specific line and given that this is handled at CPU level, it can happen that even before the next line runs, another thread has acquired the lock and updated the value.

No blocking of threads

No threads are locked in case of atomic variables. All threads just keep trying to acquire full access to a memory address until it gets it.