I sometimes use the volatile instance variable in cases where I have two threads that read / write to it and do not want the overhead (or potential risk of deadlock) to take out the lock; for example, a timer thread that periodically updates the int identifier, which is displayed as a recipient in 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 is: Given that JLS only ensures that 32-bit reads will be atomic, is there any point at ever using long-term volatile? (i.e. 64-bit).
Caution Please do not respond by saying that using volatile over synchronized is an example of preliminary optimization; I am well aware of how and when to use synchronized , but there are times when volatile is preferred. For example, when defining a Spring bean for use in a single-threaded application, I tend to use volatile instance variables, since there is no guarantee that the Spring context will initialize each bean of the property to the main thread.
java multithreading concurrency volatile
Adamski Jun 14 2018-10-14 14:49
source share