In the second example, as someone mentioned, it's not thread safe. Here's two options for making the getInstance() method thread safe:
public static synchronized Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
public static Singleton getInstance() {
if (singleton == null) {
synchronized(Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
The second version of the method allows you to get an already constructed singleton instance without any synchronization overhead. However, when it is null, you then enter a synchronized block. You check the null again just in case there was a thread context switch and a second thread actually gets into the synchronized block before you do. That ensures only a single instances is ever constructed.
Either approach should be entirely thread safe.