1. List of Java Concurrency In Practice
Copy the code code as follows:
public class Singleton {
private static class SingletonHolder {
public static Singleton resource = new Singleton();
}
public static Singleton getResource() {
return SingletonHolder.resource;
}
private Singleton(){
}
}
2. Effective Java
Copy the code code as follows:
public class Singleton {
public static final Singleton INSTANCE = new Singleton();
private Singleton(){}
public void method(){
//...
}
public static void main(String[] a){
//Call method.
Singleton.INSTANCE.method();
}
}
3. Use enumerations to cleverly create single instances
Copy the code code as follows:
/**
* Use enumerations to cleverly create single instances
*/
public enum Singleton {
INSTANCE;
public void method(){
//...
}
public static void main(String[] a){
//Call method.
Singleton.INSTANCE.method();
}
}
4. Double lock
Copy the code code as follows:
public class Singleton {
private static volatile Singleton instance = null;
/**
* Prevent others from new objects
*/
private Singleton(){
System.out.println("init");
}
public static Singleton getInstance(){
if(instance == null){
synchronized(Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}