Your getSingleton() method tries to lazily initialize an instance of SINGLETON, but it has the following problems:
- Variable access not
synchronized - The variable is not
volatile - You do not use double lock check
therefore, the AMY race condition causes the creation of two instances.
It was best and easier to safely lazily initialize a singleton without synchronization:
private static class Holder { static Singleton instance = new Singleton(); } public static Singleton getSingleton() {
This is thread safe because the java class loader contract is that all classes have static initialization before they can be used. In addition, the class loader does not load the class until it is referenced. If two calls to the getSingleton() stream at the same time, the Holder class will still be loaded only once, and thus new Singleton() will be executed only once.
This is still lazy because the Holder class only refers to the getSingleton() method, so the Holder class will only load the first time getSingleton() called.
No synchronization is required because this code uses the internal loader synchronization of the class, which is bullet proof.
This code template is the only way to fly with single player games. It:
- The fastest (no sync)
- The safest (depends on the safety of the industrial strength class loader)
- Cleanest (smallest code - double locking check - ugly and lots of lines for what it does)
Another similar code (equally safe and fast) is to use enum with a single instance, but I find this inconvenient and the intention is less clear.
source share