Java Reference
In-Depth Information
LISTING 4‐2: Synchronizing the singleton for thread safety
package com.devchronicles.singleton;
public class MySingleton {
private static MySingleton instance;
private MySingleton() {}
public static synchronized MySingleton getInstance() {
if (instance==null){
instance=new MySingleton();
}
return instance;
}
}
Another approach is to create the singleton instance at the same time you load the class, as shown in
Listing 4‐3. This prevents needing to synchronize the creation of the singleton instance and creates
the singleton object once the JVM has loaded all the classes (and therefore before a class can call
the getInstance() method). This occurs because static members and blocks are executed when the
class is loaded.
LISTING 4‐3: Creating the singleton object at the time of class loading
package com.devchronicles.singleton;
public class MySingleton {
private final static MySingleton instance=new MySingleton();
private MySingleton() {}
public static MySingleton getInstance() {
return instance;
}
}
Another approach is to use a static block, as shown in Listing 4‐4. However, this leads to lazy
initialization because the static block is invoked before the constructor is called.
LISTING 4‐4: Creating the singleton object in a static block
package com.devchronicles.singleton;
public class MySingleton {
private static MySingleton instance=null;
static {
instance=new MySingleton();
}
Search WWH ::




Custom Search