Why does Java not see the updated value from another thread?

后端 未结 5 1129
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 14:35

Please look at this code(taken from Effective Java book)

import java.util.concurrent.TimeUnit;


public class Main {
private static boolean stopReq;
public s         


        
5条回答
  •  渐次进展
    2020-11-28 15:25

    You should read more about Java Memory Model to better understand all the implications.

    Shortly, the stopReq variable not being volatile or included in a synchronized block gives the VM freedom to use an optimized local storage (eg. registers etc) which is not guaranteed to propagate changes immediately across the threads.

    When you declare the variable as volatile the VM will make sure that after each variable write a "memory write barrier" is inserted which will force all the local changes to be spilled to the real memory location thus making it visible to all the other threads (the same barrier is placed at the end of a synchronized block eg.)

提交回复
热议问题