You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单例模式(Bill Pugh实现方案)中volatile关键字的使用咨询

Bill Pugh Singleton: Why Volatile Isn’t Needed Here

Great question! Let’s unpack this step by step, since the Bill Pugh singleton is a widely loved (and often misunderstood) implementation that differs from other patterns where volatile is mandatory.

First, How the Bill Pugh Implementation Works

The core trick here is leveraging the JVM’s class initialization mechanism for thread safety:

  • The static inner class SingletonHelper isn’t loaded or initialized until the first time getInstance() is called.
  • When the JVM initializes a class, it guarantees that the initialization process is atomic and synchronized across all threads. That means the line private static Singleton INSTANCE = new Singleton(); will fully complete (object allocated, initialized, and assigned to INSTANCE) before any thread can access INSTANCE.

Why Volatile Isn’t Required Here

You’re probably thinking of the double-checked locking (DCL) singleton pattern, where volatile is critical. Let’s contrast:

  • In DCL, you create the singleton instance directly inside the getInstance() method (without a static inner class). Without volatile, the JVM might reorder the instructions of new Singleton():
    1. Allocate memory for the object
    2. Assign the uninitialized object to INSTANCE
    3. Initialize the object
      This could let another thread see a "half-initialized" instance. volatile prevents this reordering and ensures visibility across threads.
  • In the Bill Pugh pattern, the JVM’s class initialization lock takes care of this synchronization automatically. There’s no chance of a thread seeing a partially initialized INSTANCE, because the class won’t be considered initialized until the new Singleton() call is fully done.

What About the nonVolatileVariable?

Your code has a non-volatile instance variable nonVolatileVariable—this is unrelated to the singleton’s thread safety. If multiple threads are reading and writing this variable concurrently, you’d need to add synchronization (like synchronized methods) or mark it as volatile to avoid visibility issues. But that’s a separate concern from the singleton’s initialization itself.


内容的提问来源于stack exchange,提问作者Deepak Shajan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:26:20