0

I'm trying to understand creating a Singleton Object using Enum. I wrote this code. Is this threadsafe?. Please tell me if not ,how to make this

 public enum MySingleton {

    INSTANCE;
    private static final Employee emp = Employee.getInstance();
    }


public class Employee {
    private static Employee emp;

    public static Employee getInstance(){
    emp=new Employee();
    return emp;
    }
}
Anil Kumar
  • 2,521
  • 7
  • 23
  • 40

1 Answers1

0

It's not thread safe because Employee.getInstance() could be called by multiple threads and return one or more objects.

A simple solution is to make Employee an interface

public enum MySingleton implements Employee {
    INSTANCE;
}

public interface Employee {

}

This is thread safe as the construction of INSTANCE is thread safe.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130