Then wrote a main method in the same class and tried testing it:
As its the same class I was able to create a object with new operator. Here both the Objects are different and even equals prints false. Is it not the correct singleton implementation?
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.
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.
Vivek Hingorani wrote:But Whats the prob in having main method in same class?
If your constructor is private then the only way to create an instance of that class is from within the class itself.
In your class there are two methods that create instances of your class
Therefore if you want to make sure only one instance is created, get rid of your main method.
Here is the example which explains about implementation of Singleton class: Best Way to Create Singleton Class
Naveen Bachu wrote:Here is the example which explains about implementation of Singleton class: Best Way to Create Singleton Class
That's not a good example. In fact, you should avoid implementing a Singleton that way because it is not thread-safe. See Campbell's and Winston's examples instead.
It's still mislabeled as "the best way" at best, falsely advertised at worst. Don't use that method, even with synchronization. There are better ways.
I didn't get what is wrong with the code, except synchronization, Can you guide us to any best example to compare and improve our knowledge?
Naveen Bachu wrote:I didn't get what is wrong with the code, except synchronization, Can you guide us to any best example to compare and improve our knowledge?
That guidance has already been given. Read through the thread again.
See also this wikipedia entry on singleton pattern but read it carefully so you know which ones are examples of bad implementations vs which ones are good implementations.