Thread safe Java Singleton

This article is about creating a thread safe Singleton in Java, If you are looking for a thread safe Singleton in C++ please follow this link here.

When creating a Singleton there are three basic patterns you can use each has a different profile depending on what you want to do.
Firstly the Double checked locking pattern.
This is so called because we check the instance has not been created twice before attempting to create the instance which is the Singleton that we pass back from the static method. One of the concerns raised in creating a Singleton like this is after the second instance check that is done in the synchronized context ( Note we synchronise on .class as we are in a static context so no this ) we have a small window of effective vulnerability in that instance= new Sigleton() is a 3 step process
1. The JVM needs to allocate memory which can fail
2. Then the JVM needs to create the object itself and if there are issues this can be half formed
3. Then the new object needs to be assigned to instance
This is not a problem per se because the JVM will throw appropriate exceptions but there are better and safer ways of doing this sort of lazy initialization with a smaller window of vulnerability and in a more efficient manner.
Here is the code for Double checked locking:



public class DoubleCheckedSingletom {
private static volatile DoubleCheckedSingletom instance=null;

public static DoubleCheckedSingletom getInstance() {
if(instance==null) {
synchronized(DoubleCheckedSingletom.class) {
if(instance==null) {
//This is 3 step - so subtle bugs can creep in
//Allocate memory and
//Create the Singleton
//assign back to instance
instance= new DoubleCheckedSingletom();
}
}
}
return instance;
}




The other way to create a Singleton is to create it using either upfront initialization or lazy initialization. Recall static initialisations are created at class instantiation time before constructors run so you can't get race conditions.

Here is the Upfront Initialization Singleton, note the private static class field which is set up at class instantiation.



class UpfrontStaticSingleton{
//Set up at Class load as part of Static initialization
private static UpfrontStaticSingleton instance = new UpfrontStaticSingleton();

public UpfrontStaticSingleton getInstance() {
return instance;
}
}




The other way is to perform a lazy initialization using an inner static class which again is created as needed and is done when you request the inner class. Again the inner class being static uses class initialization to prevent any race conditions.
Here is the Lazy Initialised Singleton, note the inner static class which gets initialised when it is used in the main class.



class LazyInitWithStaticGuarantees{
static class Initialize{
static LazyInitWithStaticGuarantees instance = new LazyInitWithStaticGuarantees();
}

public static LazyInitWithStaticGuarantees getInstance() {
return Initialize.instance;
}
}





People who enjoyed this article also enjoyed the following:


Blocking Queue Implementations in Java
Create a Statistics Distribution
Naive Bayes classification AI algorithm
K-Means Clustering AI algorithm
Equity Derivatives tutorial
Fixed Income tutorial


And the following Trails:

C++
Java
python
Scala
Investment Banking tutorials

HOME
homeicon






 

By clicking Dismiss you accept that you may get a cookie that is used to improve your user experience and for analytics.
All data is anonymised. Our privacy page is here =>
Privacy Policy
This message is required under GDPR (General Data Protection Rules ) and the ICO (Information Commissioners Office).