Singleton with Enum vs Singleton with Double Lock Check

I am wondering which one is best in practice in a multi-threaded environment. I understand that Singleton as an Enum type creates an instance when the class loads. Other than this, I do not see anything significant. Are there any pros and cons?

Singleton as Enumtype:

 public enum Singleton {
      INSTANCE;
      public void doSomething(){ ... }
 }

Singleton with double-checked locking:

 public class Singleton{
      private volatile static Singleton instance;

      private Singleton(){}
      public static Singleton getInstance(){
           if(instance == null){
                 synchronized(Singleton.class){
                       if(instance == null){
                           instance = new Singleton();
                       }
                 }
           }
           return instance;
      }

 }
+1
source share
3 answers

Often in multi-threaded applications, simpler and more understandable code is more suitable for work.

In my opinion, the first example is much simpler than the second, and this is important.

enum , . , , , , .

+1

Singletons, .

, , .

jdbc Singleton.

, , , Singleton.

public enum DBConnection {
  INSTANCE;
  private Connection connection;
  public Connection getConnection(){
    if(connection == null){
      instantiateConnection();
    }
    return connection;
  }
}

DBConnection.INSTANCE.getConnection();

Injection Dependency . , GUICE.

DBConnection.INSTANCE , getConnection(), DBConnection, @Inject. .

@Inject
private DBConnection dBConnection;

@Singleton Singleton, .

, , .

+1

enum singleton , .

, Double check lock, , , .

, :

public class Test{

      private static Test uniqueInstance = new Test();

      private Test(){}

      public static Test getInstance(){


             return uniqueInstance;     
         }

 }

, enum singleton.

0

All Articles