java singleton pattern using enum

There are two ways we can create singleton pattern in java.
1. create a private constructor and static method to return one instance
2. use enum.
Though the first approach is most common in use, there is a problem with it. what will happen if more than one thread trying to access the instance create code at the same time. That will eventually create more than one instances. Ofcourse we can make it thread safe but that will make even cumbersome to maintain in multi threading environment.

So this is the code for using enum to create a singleton. (Consider we need to create a singleton class called “Employee” and need to access a method called “getEmpDetails”

public enum Employee{

   public List getEmployees() {
      //  method implementation goes here

To access the method all you need to do is,


This is easy to implement and to maintain. Though some people argue the enum type is not meant for this, I leave the argument open. 🙂

2 thoughts on “java singleton pattern using enum

  1. I find the enum extremely elegant for a solution. It’s terse and built-in Java.
    It however cannot be used when the Singleton inherits from another class (java.util.Observable for example).
    In that case I think dp4j is the tersest option to implement the Singleton in Java.

    import com.dp4j.*;
    import java.util.*;

    public class Employee extends Observable{

    public List getEmployees() {
    // method implementation goes here

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s