Singleton mode (Singleton): is a common design pattern. In Java applications, singleton objects guarantee that only one instance of the object exists in a JVM.
1, lazy-type
Threads are unsafe, and multiple instances are created when multiple threads call getinstance () in parallel.
public class Singleton { private static Singleton instance; Private Singleton () {} public static Singleton getinstance () { if (instance = = null) { instance = new Singleto n (); } return instance;} }
2. A hungry man type
When the class is loaded, an instance of the class is created, whether you use it or not. Because instances of the singleton are declared as static and final variables, there is always only one instance in the runtime environment.
But its disadvantage is not lazy loading.
public class singleton{ //class loads when initializing private static final Singleton instance = new Singleton (); Private Singleton () {} public static Singleton getinstance () { return instance; }}
3. Double Locking type
One of the ways introduced in the headfirst design pattern is a more complex form.
The primary purpose of the double lock is to solve the need for thread waits each time the instance is fetched, and the synchronization mechanism is enabled only when the first instantiation is performed, improving performance.
However, using the volatile keyword may mask some of the necessary code optimizations in the virtual machine, so the operation is not very efficient.
public class Singleton { Private volatile static Singleton instance;//declared as volatile private Singleton () {} PU Blic static Singleton Getsingleton () { if (instance = = null) { synchronized (singleton.class) { if (instance = = null) { instance = new Singleton ();}} } return instance; } }
4. Static internal class
One of the more respected practices is said to be invented by Google Daniel. This approach cleverly uses the JVM itself to ensure thread safety.
This method does not synchronize when the instance is read, there is no performance flaw.
public class Singleton { private static class Singletonholder { private static final Singleton INSTANCE = new Sing Leton (); } Private Singleton () {} public static final Singleton getinstance () { return singletonholder.instance; } }
5. Enum Enumeration mode
The method recommended in effective Java. This is generally the best way to implement Singleton.
The biggest advantage is simplicity, and provides a serialization mechanism that absolutely prevents multiple instantiations, even in the face of complex serialization or reflection attacks.
public enum enumsingleton{ INSTANCE;}
As simple as this, you can call it using Enumsingleton.instance.
Java Implementation Singleton Pattern summary