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?
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:
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).