top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

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

+2 votes
4,235 views
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{
    INSTANCE;
        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
Singleton.INSTANCE.show();

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
...