I'm trying to better understand how does the JIT compiler work for java in respect to volatile variable value caching. Consider the example presented in this question: Infinite loop problem with while loop and threading:
boolean loaded = false; // not volatile!!!
private boolean loadAsset() {
new Thread(new Runnable() {
@Override
public void run() {
// Do something
loaded = true;
}
}).start();
while (!loaded) {
System.out.println("Not Loaded");
}
System.out.println("Loaded");
return false;
}
Since the variable loaded is not declared volatile, the JIT compiler is allowed to "cache" the variable in the registry. It is said that this could in theory result in an infinite loop because the thread that executes the loop might not see that the variable was updated from another thread at some point of time.
But what exactly does "allowed" to cache mean? Is it possible for the variable to get cached sometimes, meaning that if I run this same piece of code in the same JVM (without shutting the JVM down) a million times, the JIT compiler might at some point decide to cache the variable and produce an infinite loop? Or is the JIT compiler consistent, meaning that it will either decide to cache the variable or not and that decision would stand off for all million executions of this piece of code through out the life cycle of the JVM?