DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • AI-Driven RAG Systems: Practical Implementation With LangChain
  • Injecting Implementations With Jakarta CDI Using Polymorphism
  • STRIDE: A Guide to Threat Modeling and Secure Implementation
  • Implement a Geographic Distance Calculator Using TypeScript

Trending

  • Measuring the Impact of AI on Software Engineering Productivity
  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  • Unlocking Data with Language: Real-World Applications of Text-to-SQL Interfaces

Another Singleton Implementation

How to implement the Singleton pattern in Java in five different ways.

By 
Davide Lorenzo Marino user avatar
Davide Lorenzo Marino
·
Dec. 10, 15 · Opinion
Likes (9)
Comment
Save
Tweet
Share
13.5K Views

Join the DZone community and get the full member experience.

Join For Free

The Singleton pattern is one of the most well known patterns.

There are many possible implementations of that pattern. The most common are:

  • Eager implementation.

  • Lazy implementation with single nonsynchronized check of the instance variable (only for non multithread environment).

  • Lazy implementation with synchronization over the whole method getInstance.

  • Lazy implementation with double check of instance variable.

An uncommon implementation of the Singleton pattern is the implementation with the lazy initialization holder class idiom (also known as initialize on demand holder class idiom).

Here I propose a brief description of all the most common implementation before describing the lazy initialization holder class idiom.

Eager Implementation

All implementations have two commons aspects:

  • A private constructor.

  • A public static method getInstance to retrieve the unique instance of the Singleton class.

The eager implementation builds the unique instance of the Singleton when the class is loaded in memory.

public class Singleton {
  // Builds the instance variable once loaded the Singleton class
  private static Singleton instance = new Singleton();

  private Singleton() {
    // The private constructor body
  }

  public static Singleton getInstance() {
    // Returns the already build with an eager approach instance variable
    return instance;
  }
}

Lazy Implementation Not Synchronized

The lazy implementation not synchronized works only for non multithreaded environments.

public class Singleton {
  private static Singleton instance;

  private Singleton() {
  }

  public static Singleton getInstance() {
    // Here a single check not synchronized
    if (instance == null) {
      instance = new Singleton();
    }
    return instance;
  }
}

Lazy Implementation With Whole Synchronization

Similar to the previous implementation but with a synchronized getInstance method that guarantees a correct use also in a multithread environment.

public class Singleton {
  private static Singleton instance;

  private Singleton() {
  }

  public static synchronized Singleton getInstance() {
    // Here a single check but in a synchronized getInstance method
    if (instance == null) {
      instance = new Singleton();
    }
    return instance;
  }
}

Double Check 

The previous implementation is not the best one for multithread environment because the whole method getInstance has been synchronized.

In a multithread enviroment it is better to synchronize the smallest portion of code possible.

The double check implementation try to do exactly that.

public class Singleton {
  private volatile Singleton instance;

  private Singleton() {
  }

  public static Singleton getInstance() {
    // First check 
    if (instance == null) {
      synchronized(Singleton.class) {
        // Second check inside a synchronized block
        if (instance == null) {
          instance = new Singleton();
        }
      }
    }
    return instance;
  }
}

Lazy Initialization Holder Class Idiom

A class is not initialized before it is used. Knowing that it is possible to create a new elegant implementation of the Singleton pattern.

Instead of saving the instance variable in the Singleton class, we hide it in an inner class SingletonHolder.

We define the nested class SingletonHolder as static so it is possible to use it without instantiating the Singleton. The body of the SingletonHolder has only one static final member instance that is eager initialized to a new Singleton instance.

The getInstance method of Singleton simply returns the value of the instance variable held in the SingletonHolder nested class. 

Because the class SingletonHolder is called only when somebody calls the method getInstance of the Singleton, the Singleton instance is created lazily after the first demand. 

The internal implementation of the JVM guarantees that the initialization of the SingletonHolder class is done synchronously. After the initialization, no synchronization is needed because the instance variable can't be changed (it is final). So we have a lazy creation of the instance safe in a thread environment without any explicit synchronization block.

Here's the code:

public class Singleton {
    private Singleton() {
        // The body of private constructor
    }

    public static Singleton getInstance() {
        return SingletonHolder.instance;
    }

    // Inner static class that holds a reference to the singleton
    private static class SingletonHolder {
        private static final Singleton instance = new Singleton();
    }
}


Implementation

Opinions expressed by DZone contributors are their own.

Related

  • AI-Driven RAG Systems: Practical Implementation With LangChain
  • Injecting Implementations With Jakarta CDI Using Polymorphism
  • STRIDE: A Guide to Threat Modeling and Secure Implementation
  • Implement a Geographic Distance Calculator Using TypeScript

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!