I have a doubt with singleton class
Usually we all declare a singleton class as following only
Can any one tell me other possibilities of creating singleton class?
Problem with an above approach is instance is static variable
If two threads hits my getInstance() method at the same time, same sec
Then I will have two instances for sure…
So what’s the best way to create thread safe singleton class?
Another point is I hate to use the word ‘synchronized’ directly
Their should be some approach available?
first of all make the constructor private. Otherwise someone would create a sub-class from it and create multiple instances. The solution to your second problem is either to use eager instantiation or synchronize the getInstance method. The eager instantiation would work like this
And if you want to prevent incurring the unneccesary synchronization overhead for each and every call to getInstance() you could leave the getInstance() method unsynchronized and use an initialization holder to still achieve lazy initialization. The same could be achieved using the double-checked locking approach, but that approach should ideally be avoided.
This may be the beginner forum, but I think the topic asked about is inherently more complex than is usually appropriate for this forum. Perhaps it should be moved.
The article Rob links to is a bit old. It explains the problems with double-checked locking prior to JDK 5. However in JDK 5 they improved the volatile keyword to make it a bit more useful, and now it is possible to reliably implement DCL in Java, if and only if you make your variable volatile.
More discussion of this and other approaches can be found here. Note that the comment by Allen Holub is from pretty old, and does not really apply any more. Volatile is significantly quicker than it used to be. You can also find more info here.
Joined: Oct 13, 2005
Agree with Mike S; once you get onto "volatile" you are well out of beginner's.