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() {
++id;
}
}, 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.
Not sure if I understand your question correctly, but the JLS 8.3.1.4. volatile Fields states:
and, perhaps more importantly, JLS 17.7 Non-atomic Treatment of double and long :
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 forints since not even a read is atomic for non-volatile longs/doubles.