Take the 2-minute tour ×

I occasionally use a volatile instance variable in cases where I have two threads reading from / writing to it and don't want the overhead (or potential deadlock risk) of taking out a lock; for example a timer thread periodically updating an int ID that is exposed as a getter on some class:

public class MyClass {
  private volatile int id;

  public MyClass() {
    ScheduledExecutorService execService = Executors.newScheduledThreadPool(1);
    execService.scheduleAtFixedRate(new Runnable() {
      public void run() {
    }, 0L, 30L, TimeUnit.SECONDS);

  public int getId() {
    return id;

My question: Given that the JLS only guarantees that 32-bit reads will be atomic is there any point in ever using a volatile long? (i.e. 64-bit).

Caveat: Please do not reply saying that using volatile over synchronized is a case of pre-optimisation; I am well aware of how / when to use synchronized but there are cases where volatile is preferable. For example, when defining a Spring bean for use in a single-threaded application I tend to favour volatile instance variables, as there is no guarantee that the Spring context will initialise each bean's properties in the main thread.

share|improve this question
Note, ++ are not atomic operations. I suggest using java.util.concurrent.atomic.AtomicInteger instead. –  Tom Hawtin - tackline Jun 14 '10 at 15:02
Thanks Tom - It was really just a trivial example. –  Adamski Jun 14 '10 at 15:05
By the way, you don't need to use volatile with Spring. Spring uses a lock when initializing your classes and the happens-before relations will take care of the ordering for you –  oxbow_lakes Jul 15 '10 at 23:53
add comment

1 Answer

up vote 39 down vote accepted

Not sure if I understand your question correctly, but the JLS volatile Fields states:


and, perhaps more importantly, JLS 17.7 Non-atomic Treatment of double and long :

17.7 Non-atomic Treatment of double and long
For the purposes of the Java programming language memory model, a single write to a non-volatile long or double value is treated as two separate writes: one to each 32-bit half. This can result in a situation where a thread sees the first 32 bits of a 64 bit value from one write, and the second 32 bits from another write. Writes and reads of volatile long and double values are always atomic. Writes to and reads of references are always atomic, regardless of whether they are implemented as 32 or 64 bit values.

That is, the "entire" variable is protected by the volatile modifier, not just the two parts. This tempts me to claim that it's even more important to use volatile for longs than it is for ints since not even a read is atomic for non-volatile longs/doubles.

share|improve this answer
Ah ok cool - That's exactly what I wanted to check. –  Adamski Jun 14 '10 at 14:57
add comment

Your Answer


