For singletons, you can delegate the task to the JVM code for static initialization.
public class Something {
private Something() {
}
private static class LazyHolder {
public static final Something INSTANCE = new Something();
}
public static Something getInstance() {
return LazyHolder.INSTANCE;
}
}
If you are using Apache Commons Lang, then you can use the variations o ConcurrentInitializer like LazyInitializer.
ConcurrentInitializer<Foo> lazyInitializer = new LazyInitializer<Foo>() {
@Override
protected Foo initialize() throws ConcurrentException {
return new Foo();
}
};
You can now safely get Foo( gets initialized only once)
Foo instance = lazyInitializer.get();
Want to learn Java? Check out the core java certification from Intellipaat.