SingletonDescriptionA class for which there should only be one instance in the entire system at any given time. This program detects singletons which enforce their own singularity, which means they keep one static instance of themselves and pass it around through a static getter method. CriteriaSingletons have a public static method that returns an instance of themselves, and they have at least one private static non-final field of the same type. Examplepublic class Singleton {
private static Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}For the purposes of detection, we are not interested in whether or not there is: - a private constructor
- synchronized around the new instance logic
Why? We want to be able to detect badly written Singletons too.
|
shouldn't the criteria also that the class has a singe private constructor? Otherwise it isn't exactly enforcing singularity...
The above code is NOT a singleton behaviour!!!
Ideal singleton class is:
public class Singleton {
}
The reason the earlier code does not create singleton is that in multithreaded environment, the calls to getInstance would lead to multiple calls to the constructor (though the reference is only one) and leads to multiple instances. Moreover synchronizing the getInstance() would lead to performance issues and double checking as:
public class Singleton {
}
... does not work either because of the compiler optimizations.
Even the double checked locking algorithm is broken.
There are number of sites which has shown that due to java memory model double checked locking would not guarantee singleton objects.
Have a look at this article. http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.html.
According to me the best was of doing is to be as simple and sure as possible and that is:
public class Singleton {
}
Regards, Purav Gandhi
even the double checked "wiki posting locking algoriothm" is broken...
lucky for us, the "irony" pattern is alive and well
as the wiki already said
we are not interested in whether or not there is:
Why? We want to be able to detect badly written Singletons too
But if you ( all above comments ) really wanna go into deep than override clone method and throw CloneNotSupportedException?;