Tuesday, April 13, 2010

Design patterns - Singleton


You know how to create a perfect singleton class?

This is the way to create it..

class SingClass {
private static singClass;

public SingClass getInstance() {
if (singClass == null) {
singClass = new singClass();
}
}

private SingClass() { }
}

But, will it work always?
It works perfectly if only one thread will access it any time.

But what if multiple threads access getInstance() method simultaneously?
Use double-checking method, don't know what is double-checking?
Refer to complete explanation here..
http://www.ibm.com/developerworks/java/library/j-dcl.html


It talks about, double-checking and what are its pit falls...
Nice article...

No comments: