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{
   INSTANCE;

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

To access the method all you need to do is,

Employee.INSTANCE.getEmployees();

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

Advertisements

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

    @Singleton
    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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s