Singleton with static inner class and double lock check

I read about the Singleton design pattern and evaluate various implementations. I doubt the following implementations:

a. Singleton implementation with static inner class

public class SingletonWithStaticClass {

private SingletonWithStaticClass(){}

private static class SingletonInnerClass{
    public static SingletonWithStaticClass INSTANCE = new SingletonWithStaticClass();

}

public static SingletonWithStaticClass getInstance(){
    return SingletonInnerClass.INSTANCE;
}

}

W. Singleton with double lock check

public class SingletonWithDoubleCheck {
private static SingletonWithDoubleCheck INSTANCE = null;

private SingletonWithDoubleCheck(){
    if(INSTANCE != null){
        throw new RuntimeException("Accessing private constructor is prohibited. Use getInstance method instead");
    }
}

public static SingletonWithDoubleCheck getInstance(){
    if(INSTANCE == null){
        synchronized (SingletonWithDoubleCheck.class) {
            if(INSTANCE == null){
                INSTANCE = new SingletonWithDoubleCheck();
            }
        }
    }
    return INSTANCE;
}

}

Which one is better?

I feel that we can access the private constructor with Reflection in the first implementation, where the second implementation is safe (From Reflection attack).

However, I am not going to use any of them in my production code, I will use enum instead . But of these two, is not the first implementation broken when the reflection attack is considered?

Please correct me if my understanding is wrong.

+4
2

. Java 5.0, . Java 5.0, volatile, enum

enum . final, , , private.

enum Singleon {
    INSTANCE;
}

, . Dependency Injection / , .

+6

- .

, , , , .

synchronized, .

+1

Source: https://habr.com/ru/post/1622096/


All Articles