Atomic Assignments

Not all assignments operations in Java are atomic. Learn what types can be atomically assigned according to the Java specification.

We'll cover the following...

Overview

Multithreading revolves around the ability to execute actions atomically, that is without interference from other threads. We use various language provided constructs to ensure that critical sections of code are executed atomically. However, this also begs the questions, what operations are performed atomically by the language. For instance we already know that incrementing an integer counter as follows is never thread-safe:

counter++;

The above expression breaks down into several lower-level instructions that may or may not be performed atomically and therefore we can’t guarantee that the execution of this expression is thread-safe. However, what about simple operations such as an assignment? Consider the following:

void someMethod(int passedInt) {
   counter = passedInt; // counter is an instance variable
}

If several threads were to invoke ...