Why is volatile used in double checked locking

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

    If you didn't have it, a second thread could get into the synchronized block after the first set it to null, and your local cache would still think it was null.

    The first one is not for correctness (if it were you are correct that it would be self defeating) but rather for optimization.

提交回复
热议问题