Reputation: 21885
Consider the Singleton :
public final class MySingleton {
private static class Nested
{
private static final MySingleton INSTANCE = new MySingleton();
}
private MySingleton()
{
if (Nested.INSTANCE != null)
{
throw new IllegalStateException("Already instantiated");
}
}
public static MySingleton getInstance()
{
return Nested.INSTANCE;
}
}
I didn't put any locks , but why is this a thread safe solution for the Singleton problem ?
Upvotes: 0
Views: 74
Reputation: 280167
I didn't put any locks, but why is this a thread safe solution for the Singleton problem ?
Because class variables are initialized when their declaring classes are initialized and classes are initialized behind a lock. The process is described in the Detailed Initialization Procedure chapter of the Java Language Specification.
When your client code invokes getInstance
, the corresponding thread will try to access Nested.INSTANCE
. If Nested
hasn't been initialized, the current thread will acquire an initialization lock for the class and initialize it. Part of the initialization process will initialize the final
class field INSTANCE
.
Note that in the example you have given, there is no point in having the Nested
class be a holder for INSTANCE
, you might as well have had the field in the MySingleton
class.
Upvotes: 5