Why is volatile used in double checked locking

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

    A volatile read is not really expensive in itself.

    You can design a test to call getInstance() in a tight loop, to observe the impact of a volatile read; however that test is not realistic; in such situation, programmer usually would call getInstance() once and cache the instance for the duration of use.

    Another impl is by using a final field (see wikipedia). This requires an additional read, which may become more expensive than the volatile version. The final version may be faster in a tight loop, however that test is moot as previously argued.

    0 讨论(0)
提交回复
热议问题