Singleton pattern with combination of lazy loading and thread safety
You first design is actually lazy. Think about it, the instance is only created when the class is initialized; the class is only initialized when the getSingleton()
method is called [1]. So the instance is only created when it's asked for, i.e. it's lazily created.
[1] http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4.1
The best way is actually to use the Enum Way:
public enum Singleton {
INSTANCE;
public void execute (String arg) {
//... perform operation here ...
}
}
Your second code snippet is, in my opinion, the best way of thread-safe lazily initializing a singleton. It actually has a pattern name
Initialization-on-demand holder idiom
I would suggest you use it.
The second one is very bad in terms of readability, first one is suitable. Have a look at this article. Its about double check locking, but also will give you wide information about singletons multithreading.