Single-Case mode
1. A Hungry man mode: Create an instance when the class is loaded (thread-safe)
2. Lazy mode: Create an instance (thread unsafe) solution when the method is run: double-check
A Hungry man mode:
Public classSingleton {//a hungry man mode//privatize a constructor PrivateSingleton () {}//instantiating an object Private StaticSingleton instance =NewSingleton (); //How to get an instance Public StaticSingleton getinstance () {returninstance; }}
Lazy mode:
//Lazy Mode//privatize a constructor PrivateSingleton () {}//instantiating an object Private StaticSingleton instance; //How to get an instance Public StaticSingleton getinstance () {if(Instance = =NULL) {instance=NewSingleton (); } returninstance; }
Workaround 1 (slow)
// How to get an instance synchronized Public Static Singleton getinstance () { ifnull) { new Singleton (); } return instance; }
Workaround 2 (slow)
// How to get an instance Public Static Singleton getinstance () { synchronized (Singleton. Class ){ifnull) { new Singleton (); } return instance; } }
Workaround 3 (recommended)
Cause: If the instance already exists, there is no thread-safe problem, you can get the instance directly and reduce the speed problem caused by the lock.
Public classSingleton {//Lazy Mode//privatize a constructor PrivateSingleton () {}//instantiating an object Private Static volatileSingleton instance; //How to get an instance Public StaticSingleton getinstance () {if(Instance = =NULL) { synchronized(Singleton.class) { if(Instance = =NULL) {instance=NewSingleton (); } } } returninstance; }}
volatile keyword
Simple interest mode (a hungry man mode, lazy mode) thread safety and problem solving