I had a quick read of the Static-vs-Single-Pattern thread and agree that it is pretty horrendous.
To borrow from the religious tone of that thread, my 'bible' is Joshua Bloch's Effective Java (2nd Ed). On page 17 Joshua details three ways of creating a singleton,
final field
static factory, and
use an enum with one element (form 1.5 only)
I recall the Head First Patterns book also has an example in it that deals with the double locking.
Anyway, while only a beginner, I am using a couple of Singletons. I can't see an alternative for maintaining system state across the application.
Marten
when in doubt put it in parenthesis and stick a dollar sign in front of it, only good can come from this.
I think Simpletons are necessary sometimes--the trick is to actually do them right (surprisingly difficult), and make sure that references to them are injected, not hard-coded. Double-locking is pretty broken: not as bad as it was pre-1.5, but still broken (see the IBM link provided by Janeice and my followups).
I never manage Simpletons myself; I let Spring do it. I think enums are the best post-1.5 way of implementing non-Spring-esque singletons, although I'm not convinced that's really an intended enum usecase :/
swapnl patil
Ranch Hand
Joined: Aug 13, 2007
Posts: 80
posted
0
According to me Second approach is right implementation of singleton pattern . Please Go through Head first Singleton pattern book.
Raj chiru
Ranch Hand
Joined: Aug 12, 2008
Posts: 140
posted
0
Hi Friends,
Thanks For Your Replies.
But, we have any drawbacks with eagerly created instance(First code)?
But with eagerly created instance, the JVM create the unique instance of the singleton when the class is loaded.
The JVM guarantees that the instance will be created before any thread access the static singletonObject variable.
so,it is thread-safe,Right?
Marilyn de Queiroz
Sheriff
Joined: Jul 22, 2000
Posts: 9033
10
posted
0
I think the first is more thread safe than the second.
JavaBeginnersFaq "Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Raj chiru
Ranch Hand
Joined: Aug 12, 2008
Posts: 140
posted
0
Hi Marilyn,
Thanks For Your Reply.
But i think most of the people implementing the sinleton with Lazy instance creation,why?
Because at one point people thought double-locking worked (and it's less-broken in Java 1.5+, but still broken). Again, see the previous, horrendous singleton thread and read the references Janeice and I provided.
Raj chiru
Ranch Hand
Joined: Aug 12, 2008
Posts: 140
posted
0
Hi David,
Thanks For Your Reply.
David Newton wrote:Because at one point people thought double-locking worked (and it's less-broken in Java 1.5+, but still broken). Again, see the previous, horrendous singleton thread and read the references Janeice and I provided.
can we solve the "double-checked locking" with ThreadLocal class?