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

泪湿孤枕 提交于 2021-01-28 04:23:35

问题


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?


回答1:


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.




回答2:


To answer your last question, yes it is possible that the JIT decides to optimize the loop in this way after the program has run a while.

The JVM employs heuristics to decide when to compile or recompile a method at different optimization levels; the optimization in question may only happen at a particular optimization level. A degree of variability is always present with a JIT compiler.



来源:https://stackoverflow.com/questions/37348390/java-jit-compiler-optimizations-is-jit-consistent-in-respect-to-volatile-varia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!