Monday, August 20, 2012

What is Singleton pattern in Java - Example

Singleton Pattern in Java
Singleton pattern in Java is used to create a Singleton class which is accessed by single instance though out Java program life cycle.Singleton is one of the old but very useful design pattern and used in several core Java libraries including Java Development Kit (JDK); java.lang.Runtime is an example of Singleton pattern in Java. This class represent single instance of Java environment running as JVM and provides several utility method to query important details about runtime like number of available processor, Java heap memory etc. Singletons are also very popular in Java interview and one of the frequently asked question. This article contains great collection of interview question on Singleton pattern in Java and can be useful to enhance your knowledge on Singleton pattern.

How to write Singleton class in Java

What is Singleton pattern in Java ExampleSingleton 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 question asked on Java interviews, but with introduction of Java memory model in Java 5 and change in volatile variable in Java its 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 Singleton pattern in Java by using just four lines of code as shown below :

public enum Java5Singleton{

What is benefit of using Enum to implement Singleton pattern?
There are number of advantage to use Enum to implement Singleton pattern in Java :

1) Singleton instance is thread-safe because JVM guarantees that Enum instances are created in thread-safe manner.
2) JVM also guarantee to maintains Singleton status when Singleton class implements Serializable which is still possible without Enum by using readResolve() method but tedious and complicated.

In Summary Singleton is very useful design pattern and Java programmer 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.

Java tutorials for beginners:

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.