Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Design Pattern (JAVA) : Singleton Pattern -- multithreaded

"In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed." -- wiki

The general idea behind Lazy Initialization is to preserve memory in a resource constrained runtime environment; however, in some cases, lazy initialization puts system stability at risk due to failed initialization at runtime.

In a multi-threaded Java program, making class Constructor Private and check for singularity in getInstance() method is insufficient. When two threads invoke the getInstance() method simultaneously, there is still possibility of double instances being created due to interleaving.

1) using early initialization is one option to tackle the problem here. Object is created immediately when class is loaded in JVM. Thus, there is no interleaving issues. However, this could sacrifice some system performance.

2) making getInstance() method synchronized is another option; however, this is not absolutely necessary as the real problem here is that we wish to make the singularity checking portion synchronized only. Creating a synchronized method is an overkill.

3) Since JDK 1.5, we can use the 'enum' keyword to achieve this:

public enum Singleton {

INSTANCE;

//Singleton method
public void someMethod( ) {...}
}
Accessing the enum Singleton :
Singleton.INSTANCE.someMethod( );

4) Finally the so called 'double checked locking' method:

public class Singleton {

/** The unique instance **/
private volatile static Singleton instance;

/** The private constructor **/
private Singleton() {}

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

return instance;
}
}
[note, the getInstance() method is static method, thus we can not use synchronized(this) statement.

According to the JLS, variables declared volatile are supposed to be sequentially consistent, and therefore, not reordered.


This post first appeared on Always Remember, You Are At Most Yourself; And, Yo, please read the originial post: here

Share the post

Design Pattern (JAVA) : Singleton Pattern -- multithreaded

×

Subscribe to Always Remember, You Are At Most Yourself; And, Yo

Get updates delivered right to your inbox!

Thank you for your subscription

×