1, a hungry man-type single case
Copy Code code as follows:
public class Singleton {
Private final static Singleton INSTANCE = new Singleton ();
Private Singleton () {}
public static Singleton getinstance () {
return INSTANCE;
}
}
2, with the help of the internal class
is a lazy single example, because the Java mechanism stipulates that the inner class Singletonholder is loaded (lazy) only when the getinstance () method is first invoked, and that its loading process is thread safe. An instance is instantiated once the inner class is loaded.
Copy Code code as follows:
public class Singleton {
Private Singleton () {}
private Static Class Singletonholder {
Private final static Singleton INSTANCE = new Singleton ();
}
public static Singleton getinstance () {
return singletonholder.instance;
}
}
3. General Locking Solution
Copy Code code as follows:
public class Singleton {
private static Singleton instance = NULL;
Private Singleton () {}
public static synchronized Singleton getinstance () {
if (instance = = null) {
Instance = new Singleton ();
}
return instance;
}
}
Although thread-safety issues are resolved, but each thread calls the getinstance to be locked, and we want to lock only the first time the getinstance is invoked, consider the following dual detection scheme
4, double detection, but pay attention to the wording
Copy Code code as follows:
public class Singleton {
private static Singleton instance = NULL;
Private Singleton () {}
public static Singleton getinstance () {
if (instance = = null) {
Synchronzied (Singleton.class) {
Singleton temp = instance;
if (temp = null) {
temp = new Singleton ();
Instance = Temp
}
}
}
return instance;
}
}
Because of the order reordering problem, you cannot write directly to the following:
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;
}
}
However, if the instance instance variable is volatile decorated, the volatile modifier can ensure that instance = new Singleton (), and that the corresponding instruction is not reordered, as the following singleton code is thread safe:
public class Singleton {
Private static volatile Singleton instance = null;
Private Singleton () {}
public static Singleton getinstance () {
if (instance = = null) {
Synchronzied (Singleton.class) {
if (instance = = null) {
Instance = new Singleton ();
}
}
}
return instance;
}
}