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 JavaSingleton 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 :
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: