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?
女神的闺蜜爱上我2017-06-23 09:16:04
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;
}
代言2017-06-23 09:16:04
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).