There are 3 ways to create a singleton in java.
eager initialization singleton
public class Test {
private static final Test TEST = new Test();
private Test() {
}
public static Test getTest() {
return TEST;
}
}
lazy initialization singleton (thread safe)
public class Test {
private static volatile Test test;
private Test(){}
public static Test getTest() {
if(test == null) {
synchronized(Test.class) {
if(test == null){test = new Test();}
}
}
return test;
}
}
Bill Pugh Singleton with Holder Pattern (Preferably the best one)
public class Test {
private Test(){}
private static class TestHolder {
private static final Test TEST = new Test();
}
public static Test getInstance() {
return TestHolder.TEST;
}
}