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

后端 未结 5 1138
隐瞒了意图╮
隐瞒了意图╮ 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:29

    To be very specific about your query, to take full advantage of the performance of modern multiprocessor hardware, in absence of synchronization, JVMs allowed to permit compiler to re-order operations and cache values in registers and in processor specific caches. As main thread writes to stopReq without synchronization so because of reordering and caching the BTW thread might never see the written value and loop forever.

    When you use synchronization or volatile they guarantee VISIBILITY and force compiler not to cache and flush changes to main memory.

提交回复
热议问题