Why is volatile used in double checked locking

后端 未结 7 1068
太阳男子
太阳男子 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:23

    Double checked locking is a technique to prevent creating another instance of singleton when call to getInstance method is made in multithreading environment.

    Pay attention

    • Singleton instance is checked twice before initialization.
    • Synchronized critical section is used only after first checking singleton instance for that reason to improve performance.
    • volatile keyword on the declaration of the instance member. This will tell the compiler to always read from, and write to, main memory and not the CPU cache. With volatile variable guaranteeing happens-before relationship, all the write will happen before any read of instance variable.

    Disadvantages

    • Since it requires the volatile keyword to work properly, it's not compatible with Java 1.4 and lower versions. The problem is that an out-of-order write may allow the instance reference to be returned before the singleton constructor is executed.
    • Performance issue because of decline cache for volatile variable.
    • Singleton instance is checked two times before initialization.
    • It's quite verbose and it makes the code difficult to read.

    There are several realization of singleton pattern each one with advantages and disadvantages.

    • Eager loading singleton
    • Double-checked locking singleton
    • Initialization-on-demand holder idiom
    • The enum based singleton

    Detailed description each of them is too verbose so I just put a link to a good article - All you want to know about Singleton

提交回复
热议问题