When will the java local memory be flushed to the main memory?

in multithreading, when will the values in the local thread in thread 1 be flushed to the main memory? What sometimes flushes to the main memory and sometimes doesn"t?

Mar.31,2021

I don't think we should think about this from refresh to main memory. We should consider JMM's Happens-Before rules. Take a look at the code first:

   
then a related answer:

Let's see what the docs actually says: The compiler is free to read the field this.done just once, and reuse the cached value in each execution of the loop. This would mean that the loop would never terminate, even if another thread changed the value of this.done.
See the highlighted word "free"? "free" means that the compiler can either read this.done once, or not. It's the compiler's choice. That's what "free" means. Your loop breaks because the compiler sees your code and thought "I am going to read iv.stop every time, even though I can read it just once." In other words, it is not guaranteed to always break the loop. Your code behaves exactly as the docs say.
Menu