mdzh mdzh - 1 year ago 64
Java Question

Java JIT compiler optimizations - is JIT consistent in respect to volatile variables value caching?

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() {

public void run() {

// Do something
loaded = true;


while (!loaded) {
System.out.println("Not 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?

Answer Source

Caching here happens on the hardware level where the CPU might decide to read the value of the variable from its cache discarding what other threads have written on their own caches.

The JIT however, might optimise the loop and turn it into and infinite loop because the boolean flag is not set inside the loop, which is not necessary the same as reading a stale value from the cache.

"Allowed to cache" here might be interpreted as, the JIT is not obliged to issue a fence instruction upon reading the variable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download