I have read about many possible ways to create a singleton for the multithreaded environment in Java, like Enums, Double-check locking, etc
.
I found a simple way that is also working fine and I unable to find its drawbacks or failure cases. May anyone explain when it may fail or why we should not choose this approach.
public final class MySingleton {
public final static MySingleton INSTANCE = new MySingleton();
private MySingleton(){}
}
I am testing it with the below code and working fine:
public class MyThread {
public static void main(String[] args) {
for (int i = 0; i < 10000; i++) {
Thread thread = new Thread(() -> {
MySingleton singleton = MySingleton.INSTANCE;
System.out.println(singleton.hashCode() + " " + Thread.currentThread().getName());
});
thread.start();
}
}
}
Every comment is appreciated.
question from:
https://stackoverflow.com/questions/65882352/multithreaded-singleton 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…