Thread Safe singleton class in java

Thread Safe singleton class in java

A thread-safe singleton class in Java ensures that only one instance of the class is created, and that instance is safely accessible from multiple threads. There are several ways to implement a thread-safe singleton in Java. Here, I'll show you two commonly used approaches: using the "Lazy Initialization with Double-Checked Locking" and "Initialization-on-demand holder idiom."

1. Lazy Initialization with Double-Checked Locking:

public class Singleton { private static volatile Singleton instance; private Singleton() { // Private constructor to prevent instantiation from other classes. } public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } } 

In this approach:

  • The getInstance method first checks if the instance is already created (instance != null) before entering the synchronized block. This avoids synchronization overhead when the instance is already initialized.
  • Within the synchronized block, it checks again if the instance is null to ensure only one thread creates the instance.
  • The volatile keyword ensures that changes made to the instance variable are visible to all threads.

2. Initialization-on-demand holder idiom (Bill Pugh Singleton):

public class Singleton { private Singleton() { // Private constructor to prevent instantiation from other classes. } private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.INSTANCE; } } 

In this approach:

  • The Singleton class contains a private static inner class (SingletonHolder) that holds the singleton instance.
  • The JVM ensures that the inner class is loaded lazily and only when getInstance() is called, making it a safe and efficient way to create a thread-safe singleton.

Both of these approaches ensure thread safety and lazily initialize the singleton instance when it's first requested. The Initialization-on-demand holder idiom is often considered a cleaner and more efficient way to implement a thread-safe singleton in Java, as it doesn't require explicit synchronization.


More Tags

bisect google-apps tableview jenkins-cli json-deserialization encoder node-red bit-shift ssms-2017 parameters

More Java Questions

More Internet Calculators

More Trees & Forestry Calculators

More Housing Building Calculators

More Statistics Calculators