Monday, September 11, 2023

How to create a thread-safe Singleton in Java using Enum [Example]

Hello guys, the Singleton pattern in Java is used to create a Singleton class that is accessed by a single instance though out the Java program life cycle. Singleton is one of the old but very useful design patterns and used in several core Java libraries including Java Development Kit (JDK); java.lang.Runtime is an example of a Singleton pattern in Java. This class represents a single instance of Java environment running as JVM and provides several utility methods to query important details about runtime like a number of available processors, Java heap memory, etc.

Singletons are also very popular in Java interviews and one of the frequently asked questions. This article contains a great collection of interview questions on the Singleton pattern in Java and can be useful to enhance your knowledge of the Singleton pattern.

But implementing Singleton which can work in real-world scenarios is difficult as ensuring a singleton instance during concurrent Java applications and during Serialization has been a tricky problem for many Java developers. 

Thankfully, you can solve all those problems easily by using Enum to implement the Singleton patterns in Java and that's what you will learn in this Java tutorial. 

By the way, if you are new to design patterns in Java then I also suggest you check out the Design Patterns in Java course on Udemy. This course covers both SOLID design principles like Open Closed and Liskov substitution, and all-important Object Oriented design patterns like Decorator, Observer, Chain of Responsibility, and much more





How to Create Singleton class in Java with Enum?

Singleton pattern is often implemented either using lazy loading or by using double-checked locking, which was not safe and broker in Java 1.4, In short, before Java 5 writing Singleton was very difficult and one of the tricky interview questions asked on Java interviews.

But, with the introduction of the Java memory model in Java 5 and the change in a volatile variable in Java, it's possible to write thread-safe singleton using double-checked locking. Java 5 also introduced Enum in Java, which is the best choice to implement thread-safe Singleton in Java

You can now implement the Singleton pattern in Java by using just four lines of code as shown below:

public enum SingletonImpl{
 SINGLETON;
}

This was the simplest way to implement the Singleton Design pattern in Java.  Can you think of a simpler approach to creating Singleton in Java?

And, If you are serious about learning design patterns and principles, you can also join the Design Pattern Library course on Pluralsight, which explains and teaches most of classic OOP design patterns which can help you create better code. 

Singleton in Java using Enum [Example]




Benefits of using Enum to implement a Singleton pattern?

There are a number of advantage to use Enum to implement the Singleton pattern in Java:

1. Singleton instance is thread-safe because JVM guarantees that Enum instances are created in a thread-safe manner.

2. JVM also guarantees to maintain Singleton status when Singleton class implements Serializable which is still possible without Enum by using readResolve() method but tedious and complicated.


That's all about how to use Enum to implement Singleton classes in Java. You can solve many concurrent and serialization-related issues associated with singleton patterns by using Enum as Java can do the hard work for you.  

In Summary, Singleton is a very useful design pattern and Java programmers must be familiar with what is Singleton in Java, how to create Singleton classes, issues faced to maintain Singleton status, etc. By using Enum as Singleton, we get some benefits in terms of these issues.

Though, I don't advise using Singleton anymore unless you absolutely need it as dependency injection is much better and code written using dependency injection are easier to test. If you are using framework like Spring or Google Guice then you don't need Singleton. 


Other Java Design Patterns tutorials you may like
  • Top 5 Courses to learn Design Pattern in Java (courses)
  • 5 Free Courses to learn Object Oriented Programming (courses)
  • Difference between Factory and Dependency Injection Pattern? (answer)
  • Top 5 Courses to learn Microservices in Java with Spring (courses)
  • How to create thread-safe Singleton in Java? (example)
  • How to implement the Strategy Design Pattern in Java? (example)
  • Difference between Factory and AbstractFactory Pattern? (example)
  • 18 Java Design Pattern Interview Questions with Answers (list)
  • How to design a Vending Machine in Java? (questions)
  • 20 System Design Interview Questions (list)
  • Difference between State and Strategy Design Pattern in Java? (answer)
  • Top 5 Courses to learn Design Patterns in Java (courses)
  • 5 Free Courses to learn Data Structure and Algorithms (courses)
  • My favorite courses to learn Software Architecture (courses)

Thanks for reading this article so far. If you like this Java tutorial then please share them with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are looking for some free courses to learn Design Pattern and Software Architecture, I also suggest you check out the Java Design Patterns and Architecture free course by John Purcell on Udemy. It's completely free, all you need to do is create an Udemy account to access this course. 

1 comment:

  1. There are many ways to implement Singleton pattern in Java, not just using Enum e.g

    1) Using nested Static Class for lazy initialization.

    2) Eagerly Initialized Singleton
    3) Singleton with double checked Locking with volatile variable post Java 5

    There are lots of good articles on How to write Singleton in Java, which describe these way in good detail.

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.