Is this implementation of a thread-safe singleton correct? And how can it be implemented without synchronized and volatile?

private static Singleton instance; private static Lock lock = new ReentrantLock(); private static AtomicBoolean flag = new AtomicBoolean(); public static TaxiCompany getInstance() { if (!flag.get()) { lock.lock(); try { if (instance == null) { instance = new TaxiCompany(); flag.set(true); } } finally { lock.unlock(); } } return instance; } 
  • Enum to help you - polk1lo
  • I think you'd better look in the direction of a private class constructor where it’s safer. - And
  • Perhaps help AutomaticReference.updateAndGet. Java 8 - Sergey

1 answer 1

As it was rightly noted in the comments, Singleton can be implemented using enum .

 public enum TaxyCompany { INSTANCE; private String someProperty; public String getSomeProperty() { return someProperty; } public void setSomeProperty(String someProperty) { this.someProperty = someProperty; } } 

Then we use

 public class Main { public static void main(String[] args) { TaxyCompany singleton = TaxyCompany.INSTANCE; singleton.setSomeProperty("Property value"); System.out.println(singleton.getSomeProperty()); } } 

Such an implementation will be thread safe by default.

The practice of using enum as a singleton is described in the book Effective Java (by Joshua Bloch)

  • Cleverly invented. What to do if a singleton has to implement some kind of interface or extend a superclass? Or just want to create an instance only when necessary? - Sergey
  • @Sergey, an enumerated type in Java is also a class that is implicitly inherited from java.lang.Enum . Therefore, you cannot make enum TaxyCompany extends SomeClass , but you can easily implement as many interfaces as you want enum TaxyCompany implements Runnable . What is even more interesting is that you can add abstract methods to enum, and then every element of enum will have to implement it. You can read about it here - Ruslan