The singleton pattern ensures that there is exactly one instance of a class.
There are multiple ways to implement the Singleton Pattern in Java, here is my personal favorite:
public final class SomeClass { private static final class SingletonHolder { private static final SomeClass INSTANCE = new SomeClass(); private SingletonHolder() {} } private SomeClass() { // Add code if needed } /** * @return the Singleton Instance. */ public static SomeClass getInstance() { return SomeClass.SingletonHolder.INSTANCE; } // add other methods }
Notes:
- Replace SomeClass with the class name, keep all other names exactly as given.
- Class is final to ensure its constructor cannot be made public by subclassing.
- The SingletonHolder nested class enables lazy loading and ensures synchronization without performance loss.
- Constructor must be made private.
- getInstance returns the singleton instance of this class.
is this thread safe? i've always put the assignment of the static variable in the constructor, guarded by a lock clause...
ReplyDeleteYes, this is Thread safe. The trick is that the static assignment is handled by the classloader, which is thread safe by definition (and 'faster' in locking than using synchronized{} )
ReplyDeleteNice article. just to add
ReplyDeleteWhile writing Singleton class you also need to consider following points :
1) Lazy initialization
2) Early initialization
3) Serialization
4) Many ClassLoaders
5) Cloning
Thanks
Javin
Singleton Pattern in Java
Nice Post.
ReplyDeletehttp://sde-cthsmoodle.cthss.cen.ct.gov/mahara/view/artefact.php?view=1090&artefact=2479
https://www.techrepublic.com/pictures/photos-the-top-10-computer-security-applications-of-2019/
https://yp.scmp.com/news/hong-kong/article/111710/hong-kong-weather-forecast-predicts-temperatures-cold-12-degrees
http://www.juntadeandalucia.es/averroes/centros-tic/41010198/helvia/bitacora/index.cgi
https://www.univie.ac.at/stv-biologie/forum/viewtopic.php?f=14&t=21178&p=234171