Reprint Please specify the Source:Jiq ' stechnical Blog
1. A Hungry man type
public class Singleton { private final static Singleton INSTANCE = new Singleton (); Private Singleton () {} public static Singleton getinstance () { return INSTANCE;
Cons: Allocates space when a class is loaded. If not used, it takes up more memory space.
2, lazy-type 2.1 normal lock mode
public class Singleton { private static Singleton instance = null; Private Singleton () {} public static synchronized Singleton getinstance () { if (instance = = null) { instance = New Singleton (); } return instance;
Cons: Each thread calls getinstance to be locked, inefficient, and we want to lock only on the first call to GetInstance. Consider the following double detection scheme
2.2 Placeholder Mode(recommended)
is a lazy-type singleton, as defined by the Java mechanism. The inner class Singletonholder is only loaded (and lazy) when the getinstance () method is first called, and its onboarding process is thread-safe. An instance is instantiated once when the inner class is loaded.
public class Singleton { private Singleton () {} Privatestatic class Singletonholder { //inner class. Only load on first use, and only Singletonholder class can access//special note: Changing shared variables in the static domain is thread-safe, guaranteed by the JVM static Singleton INSTANCE = new Singleton () ; } public static Singleton getinstance () { return singletonholder.instance; }}
2.3 Double Detection
Common Double detection:
public class Singleton { private static Singleton instance = null; Private Singleton () {} public static Singleton getinstance () { if (instance = = null) { synchronzied ( Singleton.class) { if (instance = = null) { instance = new Singleton ();}} } return instance;} }
Disadvantages: Command rearrangement problem, referenceThis article of mine.
How to resolve:
The instance instance variable can be modified with a volatile modifier, and the volatile modifier will ensure that instance = new Singleton (); the corresponding instruction is not reordered:
public class Singleton { private static volatile singletoninstance = null; The Volatilekeyword modifier prevents the command from being re-ordered by private Singleton () {} //constructor to be privately protected from being instantiated with public static Singleton getinstance ( { if (instance = = null) { //double check synchronzied (singleton.class) { if (instance = = null) { Instance = new Singleton ();}} } return instance;} }
Java Concurrency: A single instance of thread-Safe mode