Thread-safe setting of a variable (Java)?

Replacing references is safe. See Java language Specification:

When a thread uses the value of a variable, the value it obtains is in fact a value stored into the variable by that thread or by some other thread. This is true even if the program does not contain code for proper synchronization. For example, if two threads store references to different objects into the same reference value, the variable will subsequently contain a reference to one object or the other, not a reference to some other object or a corrupted reference value. (There is a special exception for long and double values; see §17.4.)


volatile guarantees atomicity, visibility and acts as a 'memory barrier' (google for it, if you want to know what that means) - at least since Java 5. Therefore it does exactly what you want.

Tags:

Java