A hungry man mode: Singleton mode, that is, no matter when used, when the class is loaded to instantiate an object of this class
And then wait until you use the same instance object
Benefits: Using this approach in a multi-threaded environment, you can avoid the conflicts caused by multithreading. In response, lazy mode (on-demand instantiation)
Class Singleton1{private Singleton1 () {}private static Singleton1 S1 = new Singleton1 ();p ublic static Singleton1 Getsingle ton () {return s1;}}
Lazy Mode: Single-case mode,
Benefit: Initialize the instance object until it is used, avoiding wasted memory
Cons: You'll encounter thread safety issues
Class Singleton2{private Singleton2 () {}private static Singleton2 s2 = null;public static Singleton2 GetSingleton2 () {if ( S2 = = null) {s2 = new Singleton2 ();} return s2;}}
Registration mode: With the help of an inner class, a lazy singleton, because the Java mechanism stipulates that
The inner class Singletonholder is loaded only when the getinstance () method is first called (lazy is implemented),
and its loading process is thread-safe, so this pattern overcomes the drawbacks of lazy and a hungry man patterns
Class Singleton3{private Singleton3 () {}private static class Singleholder{private final static Singleton3 s3 = new Singleto N3 ();} public static Singleton3 GetSingleton3 () {return singleholder.s3;}}
Common locking solves the thread safety problem of Singleton mode
Analysis: Although thread safety issues are resolved, each thread calls getinstance to lock,
We want to add locks only when we call getinstance for the first time, we need to improve
Class Singleton4{private static Singleton4 s4= null;private Singleton4 () {}public static synchronized Singleton4 GetSingleton4 () {if (S4 = = null) {s4 = new Singleton4 ();} return S4;}}
A discussion of the syntax and thread safety of a singleton pattern