Reading shared variable from another thread (Effective Java #66)

前端 未结 4 596
借酒劲吻你
借酒劲吻你 2021-01-05 09:13

In Effective Java: item 66, Joshua Bloch gave an example about life failure:

// Broken! - How long would you expect this program to run
class StopTh         


        
4条回答
  •  感情败类
    2021-01-05 09:39

    Since you are not telling the thread that stopRequested is a value that can be modified from outside that thread there are no guarantees that the while will evaluate to the most recent value of the variable.

    This is why the volatile keyword is useful in this situation, because it will explicitly enforce that stopRequested value, when read, will be the most recent value set by any thread.

    There are further considerations, actually from the point of view of the thread, stopRequested is a loop invariant, since it is never set by only read, so optimization choices should be considered too: if a value is thought not to be modified then there is no reason to evaluate it on each iteration.

提交回复
热议问题