I read few articles on volatile Thread cache and found either it is too much brief without examples, so it is very difficult for beginner to understand.Please help me in understanding below program,public class Test { int a = 0; public static void main(String[] args) { final Test t = new Test(); new Thread(new Runnable(){ public void run() { try { Thread.sleep(3000); } catch (Exception e) {} t.a = 10; System.out.println("now t.a == 10"); } }).start(); new Thread(new Runnable(){ public void run() { while(t.a == 0) {} System.out.println("Loop done: " + t.a); } }).start(); }}When I make a variable volatile and run my program then it stops after some time but when I remove volatile to a variable, then it goes on and my program is not stopping.What I knew about volatile is "when variable is declared as volatile then thread will directly read/write to variable memory instead of read/write from local thread cache.if not declared volatile then one can see delay in updation of actual value."Also, as per my understanding of refreshing the cached copy, I thought program will stop in some time but then why in above program it is continuing to run and not updating.So when is Thread referring to its local cache starts referring to main copy or refresh its value with main copy value?Please correct me if I am wrong in my understanding....Please explain me with some small code snippet or link. 解决方案 To begin with, the above statements are false. There are many more phenomena going on at the level of machine code which have nothing to do with any "thread-local variable caches". In fact, this concept is hardly applicable at all.To give you something specific to focus on, the JIT compiler will be allowed to transform your codewhile(t.a == 0) {}intoif (t.a == 0) while (true) {}whenever t.a is not volatile. The Java Memory Model allows any variable accessed in a data race to be treated as if the accessing thread was the only thread in existence. Since obviously this thread is not modifying t.a, its value can be considered a loop invariant and the check doesn't have to be repeated... ever. 这篇关于Java将线程缓存刷新到实际副本时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!