Why is volatile used in double checked locking

后端 未结 7 813
太阳男子
太阳男子 2020-11-22 05:01

From Head First design patterns book, the singleton pattern with double checked locking has been implemented as below:

public class Singleton {
            


        
7条回答
  •  抹茶落季
    2020-11-22 05:24

    Declaring the variable as volatile guarantees that all accesses to it actually read its current value from memory.

    Without volatile, the compiler may optimize away the memory accesses to the variable (such as keeping its value in a register), so only the first use of the variable reads the actual memory location holding the variable. This is a problem if the variable is modified by another thread between the first and second access; the first thread has only a copy of the first (pre-modified) value, so the second if statement tests a stale copy of the variable's value.

提交回复
热议问题