单例模式(Bill Pugh实现方案)中volatile关键字的使用咨询
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
SingletonHelperisn’t loaded or initialized until the first timegetInstance()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 toINSTANCE) before any thread can accessINSTANCE.
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). Withoutvolatile, the JVM might reorder the instructions ofnew Singleton():- Allocate memory for the object
- Assign the uninitialized object to
INSTANCE - Initialize the object
This could let another thread see a "half-initialized" instance.volatileprevents 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 thenew 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

