Java – is this singleton thread safe?

I have a singleton server instance, and I'm curious if my code is thread safe I've read for different singleton modes, I think the usual method is to double check the locking mode, as shown below:

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

This is considered an effective thread - safe way to set / get details I have read that the easiest way to get and set a singleton is to delay instantiation, as shown below:

public static ClassicSingleton getInstance() {
    if(instance == null) {
        instance = new ClassicSingleton();
     }
     return instance;
}

Now I want to know if my variant is thread safe My code:

public static void startServer(int listeningPortNumber) throws IOException {
    if (server != null) {
        throw new IOException("Connection exists");
    }

    server = new Server(listeningPortNumber);
}

My code is very similar to the lazy instantiation pattern above, but I can't see how my code is not thread safe Is there anything I don't see, or is this really effective code?

reference resources: http://www.javaworld.com/article/2073352/core-java/simply-singleton.html

Solution

It's not safe

Imagine what happens if two threads call startserver at the same time (or close enough to it):

>Thread a checks the server= Null and see that the server is empty - so it will not throw an exception > so is thread b > thread a now instantiates a new server (listeningportnumber); > Thread B does the same thing, and something bad may have happened during the second instantiation

If the server is not volatile, the problem is even worse because you don't even need to interleave - thread a may instantiate a new server (...), but writing to the server field is' thread B has seen it for a long time (maybe forever) because it doesn't flush to main memory

However, even if the server is volatile, this method is effective due to interleaving

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>