The best way to implement Singleton:
Things to note before implementing Singleton,
1. enum2. reflection 3. serialization - volatile instance (readResolve method) 4. threadsafe - synchronized block 5. multiple classloader - MBean solution 6. lazy initialize vs early initialization 7. inner static class 8. clone
While implementing Singleton we have 2 options
1. Lazy loading
2. Early loading
Lazy loading adds bit overhead(lots of to be honest) so use it only when you have a very large object or heavy construction code AND also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization.Otherwise choosing early loading is a good choice.
Most simple way of implementing Singleton is
Everything is good except its early loaded singleton. Lets try lazy loaded singleton
So far so good but our hero will not survive while fighting alone with multiple evil threads who want many many instance of our hero. So lets protect it from evil multi threading
but it is not enough to protect out hero, Really!!! This is the best we can/should do to help our hero
This is called "Double-Checked Locking idiom". It's easy to forget the volatile statement and difficult to understand why it is necessary.
For details : http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
Now we are sure about evil thread but what about the creul serialization? We have to make sure even while deserialiation no new object is created
The method readResolve() will make sure the only instance will be returned, even when the object was serialized in a previous run of our program.
Finally we have added enough protection against threads and serialization but our code is looking bulky and ugly.Lets give our hero a make over
Yes this is our very same hero :)
Since the line private static final Foo INSTANCE = new Foo(); is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation,
and is it guaranteed to be thread safe.
And we have came so far, here is the best way to achieve everything we did is best possible way
Which internally will be treated like
That's it no more fear of serialization, threads and ugly code. Also ENUMS singleton are lazily initialized.
-Joshua Bloch in "Effective Java"
Now you might have realized why ENUMS are considered as best way to implement Singleton and thanks for your patience :)
Updated it on my blog. |
Compilation of already published Articles/Ideas/Problems-Solutions which I faced or came across over the period of time. Largely a place for me to document it as note-to-self. Nothing serious. :)
Sunday, October 27, 2013
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment