top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

Give example program for Java Singleton – Thread safe Singleton in Java using Enum?

+2 votes
Give example program for Java Singleton – Thread safe Singleton in Java using Enum?
posted Apr 28, 2015 by Joy Nelson

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Using Enum to create Singleton is by far most simple and effective way to create thread-safe Singleton in Java, as thread-safety guarantee is provided by Java programming language itself. You don't need to bother about thread-safety issue. Since Enum instances are by default final in Java, it also provides safety against multiple instance due to serialization. One point worth remembering is that, when we talk about thread-safe Singleton, we are talking about thread-safety during instance creation of Singleton class and not when we call any method of Singleton class. If your Singleton class maintain any state and contains method to modify that state, you need to write code to avoid and thread-safety and synchronization issues. Any way here is code example of creating thread safe Singleton in Java using Enum.

 public enum Singleton{
        public void show(){
        System.out.println("Singleton using Enum in Java");        }
//You can access this Singleton as Singleton.INSTANCE and call any method like below;

personal favorite is using Enum because of its simplicity, prevention of multiple instance against Serialization attack and concise code.

answer Apr 29, 2015 by Karthick.c
Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.