Is a volatile int in Java thread-safe? Is a volatile int in Java thread-safe? multithreading multithreading

Is a volatile int in Java thread-safe?


Yes, you can read from it and write to it safely - but you can't do anything compound such as incrementing it safely, as that's a read/modify/write cycle. There's also the matter of how it interacts with access to other variables.

The precise nature of volatile is frankly confusing (see the memory model section of the JLS for more details) - I would personally generally use AtomicInteger instead, as a simpler way of making sure I get it right.


[...] as in being able to be safely read from and written to without locking?

Yes, a read will always result in the value of the last write, (and both reads and writes are atomic operations).

A volatile read / write introduces a so called happens-before relation in the execution.

From the Java Language Specification Chapter 17: Threads and Locks

A write to a volatile field (ยง8.3.1.4) happens-before every subsequent read of that field.

In other words, when dealing with volatile variables you don't have to explicitly synchronize (introduce a happens-before relation) using synchronized keyword in order to ensure that the thread gets the latest value written to the variable.

As Jon Skeet points out though, the use of volatile variables are limited, and you should in general consider using classes from the java.util.concurrent package instead.


Access to volatile int in Java will be thread-safe. When I say access I mean the unit operation over it, like volatile_var = 10 or int temp = volatile_var (basically write/read with constant values). Volatile keyword in java ensures two things :

  1. When reading you always get the value in main memory. Generally for optimization purposes JVM use registers or in more general terms local memory foe storing/access variables. So in multi-threaded environment each thread may see different copy of variable. But making it volatile makes sure that write to variable is flushed to main memory and read to it also happens from main memory and hence making sure that thread see at right copy of variable.
  2. Access to the volatile is automatically synchronized. So JVM ensures an ordering while read/write to the variable.

However Jon Skeet mentions rightly that in non atomic operations (volatile_var = volatile + 1) different threads may get unexpected result.