user1249569 user1249569 - 28 days ago 12
Java Question

2 regarding Singleton pattern / Eager initialization and Synchronization

(From Wikipedia)

//Lazy initialization:

public class Singleton {

private static volatile Singleton instance = null;

private Singleton() { }

public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class){
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}


//Eager initialization:

public class Singleton {
private static final Singleton instance = new Singleton();

private Singleton() {}

public static Singleton getInstance() {
return instance;
}
}


"If the program uses the class, but perhaps not the singleton instance itself, then you may want to switch to lazy initialization."

1 - Not sure that I got it. Why should a program not use a class? Why can't I solve it by just adding attributes/methods to it? How should the constant reference change in respect to that?

2 - In lazy initialization - How would Synchronizing getInstance() rather than the code block (getting rid of the double check), influence my program, assuming multithreading occures?

Thank you.

Answer

1 - Your application may include various jars, but you won't necessarily use all of the functionality within each jar. Further, the users of your application may not use all of the functionality you've built into it. If you have a ReportABug class for example, they may never activate that functionality from the menu because you're such an awesome programmer ;-)

Static fields/methods aren't instantiated/invoked until the class is required at runtime, so your ReportABug class could have 1000's of static fields, but fingers crossed, they'll never consume any memory because the class is never loaded.

Their point is that the class that has the singleton (or more than one) may have other static methods that don't access the singleton.

2 - you could synchronise the method against the Singleton class object, but every call to the getInstance would incur the overhead, it's much cheaper just to check if instance == null (it's one machine cycle). It is possible that another thread could preempt your thread and create the instance after the outer ==null check, so both tests are required.

Comments