Home > Back-end >  The singleton pattern with volatile and synchronized keyword
The singleton pattern with volatile and synchronized keyword

Time:10-26

See some discussion of volatile usage of articles in the singleton pattern code written in the following way,
The class Singleton {
Private static volatile Singleton Singleton;

Private Singleton () {}

Public static Singleton getInstance () {
If (singleton==null) {
Synchronized (Singleton class) {
If (singleton==null) {
singleton=new Singleton();
}
}
}
return singleton;
}
}
Why do you write that?
The getInstance () written synchronization method is not just a matter of???????
Public static synchronized Singleton getInstance () {... }

Brothers have what idea, please advise, thank you.

CodePudding user response:

Synchronized on the method, high granularity, method calls frequently, each time to lock, reduce call efficiency, extremes may die lock

CodePudding user response:

The singleton pattern common questions to ask too much,
LZ themselves refer to the following link, double check lock part of description
https://blog.csdn.net/fly910905/article/details/79286680
  • Related