How to achieve Singleton using Enum in Java?

A singleton is a class that is supposed to have only one instance per JVM. The Same instance of the singleton class is reused by multiple threads.

 

1
2
3
4
5
6
7
8
9
10
public enum SingletonUsingEnum {
INSTANCE;
int value;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}

And in Your main class, using Singleton class –

1
2
3
4
5
6
7
8
9
public class EnumDemo{
public static void main(String[] args)
{
SingletonUsingEnum singleton = SingletonUsingEnum.INSTANCE;
System.out.println(singleton.getValue());
singleton.setValue(2);
System.out.println(singleton.getValue());
}
}

 

 

 

One thing to remember here is, when serializing an enum, field variables are not getting serialized. For example, if we serialize and deserialize the SingletonUsingEnum class, we will lose the value of the int value field.

 

Although writing singleton using is easy, there are two disadvantage of using this approach:

  • enums do not support lazy loading as we can achieve in traditional way of writing Singleton
  • Though it’s very very rare but if you changed your mind and now want to convert your singleton to non-singleton, enum would not allow this.

 

 

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *