This is guaranteed to be safe by the JLS. See the holder pattern: "since the class initialization phase is guaranteed by the JLS to be sequential, i.e., non-concurrent, no further synchronization is required in the static getInstance method during loading and initialization."
The holder pattern is more complex than what you want, but the important part is that static final Something INSTANCE = new Something()
is safe no matter which class it is declared in. The benefit of the holder pattern compared to what you have is that the singleton won't be initialized until the first time it is used. This is helpful if you want to access other static members in your Singleton
class when the cost of initializing the Singleton
instance is expensive.
As Lewis_McReu and user6690200 pointed out, you should declare the INSTANCE
field final
in order to ensure that you don't accidentally assign a different Singleton
instance to the variable. You should also declare a private no-argument Singleton()
constructor to prevent other instances from being created. To make it even more bulletproof, you should declare the Singleton
class final
so that you can't subclass it with a public
constructor.