Whether you should be using singletons in the first place is doubtful, but …
Where did you find that? It is a pretty poor implementation. And putting your main method in the same class is another bit of dubious design.
You are using double‑checked locking, and everybody knows double‑checked locking doesn’t work. … and they are mistaken; it does work in Java5+. I think Joshua Bloch (Effective Java™, but I don’t have my copy to hand at present) recommends you implement a singleton like this:-I think I have got that right; please check.
No need to do anything with clone(). If you don’t implement Cloneable, you can’t use clone() anyway. Similarly, don’t implement Serializable.
Joined: Jul 08, 2011
Agreed double locking doesnt work.. But Whats the prob in having main method in same class?
That is breaking my singleton and hence the doubt.
Vivek Hingorani wrote:Is it not the correct singleton implementation?
1. SingletonsAreEvil. You may also find this article useful.
2. Lazily instantiated singletons (which appears to be what you're trying to do) are doubly evil.
3. If, in spite of all the evidence, you absolutely feel you must have a singleton:is probably the easiest way to define it.
Bats fly at night, 'cause they aren't we. And if we tried, we'd hit a tree -- Ogden Nash (or should've been).
Articles by Winston can be found here