java - Can volatile solve the problem of thread-shared data security?
欧阳克
欧阳克 2017-06-23 09:14:04
0
2
924

For example, if I want to write a singleton mode, I will not use the sycrynized synchronization method and use volitile modification

private Sigleton(){
}

private static volatile Sigleton s = null;

public static Sigleton getInstance(){

    if (s==null){
    s= new Singleton();
    }
    return s;

}

Can this solve the thread safety problem?

How to understand thread visibility

If I have two threads coming in at the same time if s==null, won't two new sigleton objects be created in the end?

欧阳克
欧阳克

温故而知新,可以为师矣。 博客:www.ouyangke.com

reply all(2)
女神的闺蜜爱上我

If the overhead of new is very small, it is absolutely fine for you to write like this. But if the initialization overhead is high, you still have to use synchronized. A typical double-checked lock is written like this:

private Singleton() {}

private static volitile Singleton s = null;

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

How to understand thread visibility

Understand the memory model first.

The thread does not directly modify the variables in the main memory, but first writes its own working memory, and then synchronizes it to the main memory. If it has not been synchronized, other threads will not see the modification (they still see their own cache of working memory).

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!