Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

java - Multithreaded Singleton

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your singleton is instantiated when the class is loaded, therefore when the main method is started, it is already instantiated and from a multithreading perspective is safe.

But there are some arguments why this might not be the best approach:

  • When instantiating your singleton throws an exception, you get a nasty classloading exception which is hard to analyze, especially when you don't have a debugger to attach.
  • When instantiating takes some time, so you might don't want to do this when the class is loaded in order to minimize the startup time of your application

And additionally using singletons is not a good design as you hardcode the dependency between the client (that uses this class) and the implementation of this class. So it is hard to replace your implementation with a mock for testing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...