Question 1: Why in singleton pattern for multi-threading we need two null checks? What if we use only the outer check?
if (instance == null) {
synchronized (ABC.class) {
// What if we remove this check?
if (instance == null) {
instance = new ABC();
}
}
Question 2: What's the difference between the following:
public ABC getInstance() {
if (instance == null) {
// Difference here
synchronized (ABC.class) {
if (instance == null) {
instance = new ABC();
}
}
}
return instance;
}
private static final Object LOCK = new Object();
.
.
public ABC getInstance() {
if (instance == null) {
// Difference here
synchronized (LOCK) {
if (instance == null) {
instance = new ABC();
}
}
}
return instance;
}
if (instance == null) {
// Difference here
synchronized (new Object()) {
if (instance == null) {
instance = new ABC();
}
}
}
Using an object as the argument for synchronization is ueful if you want lock your synchronized block with a specific object instead of the class or this. This allows you to have different blocks of code using different locks in the same class. For example:
Object o1 = new Object(); Object o2 = new Object(); synchronized(o1) { //your synchronized block } synchronized(o2){ //other synchronized block }
In the previous code sample, block1 and block2 can be executing at the same time by different threads because they use a different lock object. If you were using the same lock for both blocks of code (IE the class), block 1 would be blocked until block2 completes its execution, and the other way around.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.