Threadsafe singleton has no Java synchronization?

I have a multithreaded application and a singleton class:

public final class Singleton {

    private static MyClass mc;

    public static final Object getInstance() {
            if(mc == null) {
                mc = new MyClass();
            }
            return mc;
    }

}

Of course, this does not work in general multithreading scenarios However, please consider the following situations:

>At first, there is only one thread > this thread calls getInstance () for the first time to initialize MC. > After that, the first thread starts all other threads

My hypothesis:

This should be effective because the initialization of MC fields and the construction of objects occur in all subsequent threads Before the start () call starts another thread And the thread of the thread Start() occurs before all other operations of the thread Therefore, MC initialization occurs before all operations in all other threads so that getInstance () will return the correct values for all threads

Is this assumption right? Why / why not?

Solution

Your analysis is really good

To be exact: everything that happens on a thread will happen before the relationship (obviously, it says: "if x and y are the actions of the same thread and X appears before y in the program sequence, then HB (x, y).")

Then, JLS 17.4 5 continue to say the following:

"Start() is called on the thread before starting any operation in the thread."

Therefore, there is an obvious occurrence before the sequence between singleton instantiation and started threads, so they are guaranteed to see the latest value

To put it simply: the created thread can ensure to see everything done by its parent process before creation, otherwise concurrent programming is almost impossible

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
分享
二维码
< <上一篇
下一篇>>