I am reading Esteban Herrera's Java 8 Programmer II Study Guide. I already understand the keyword "synchronized," but not "volatile." In the first chapter, the author makes the case for the "volatile" keyword. First, he points out an issue with the following code.
class Singleton {
private static Singleton instance;
private Singleton() { }
public static Singleton getInstance() {
if(instance == null) {
synchronized (Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
He calls the above code imperfect, arguing, "The JVM, or sometimes the compiler, can optimize the code by reordering or caching the value of variables (and not making the updates visible)." He recommends adding the volatile keyword to the Singleton instance field because this ensures that its read and write operations will be atomic rather than cached in the case of multiple threads.
I do not fully understand Herrera's argument. What does it mean to reorder the value of variables, and why would this be a problem? What does it mean for read/write operations in multiple threads to be atomic, and why is this necessary? Every explanation that I have found online is likewise full of jargon. Can anyone explain the volatile keyword in layman's terms without assuming a prior understanding of the above terms?