Double-checked locking optimization of server performance

Brief introduction

Earlier article discussed the asynchronous server performance optimization of queries turn sync , in this article, double-checked locking will discuss the design mode. Prior check by simply locking condition, the lock acquisition mode reduces the number of times, generally improves performance.

Here are some articles about before locks and thread-safe article:

Singleton lock Demo

First, let's look at a simple example of a single tight synchronization includes:

public class DraconianSingleton {
    private static DraconianSingleton instance;
    public static synchronized DraconianSingleton getInstance() {
        if (instance == null) {
            instance = new DraconianSingleton();
        }
        return instance;
    }
 
    // 其他方法
}复制代码

Although such is thread-safe, but we can see that there are still significant performance drawbacks: Every time we want to obtain an instance of a single case, we may need to obtain unnecessary locks.

To resolve this problem, we first need to verify whether the object is created only in this case, we can get a lock.

Furthermore, we want to execute sync blocks immediately after entering the same check again in order to maintain an atomic operation:

public class DclSingleton {
    private static volatile DclSingleton instance;
    public static DclSingleton getInstance() {
        if (instance == null) {
            synchronized (DclSingleton.class) {
                if (instance == null) {
                    instance = new DclSingleton();
                }
            }
        }
        return instance;
    }
 
   // 其他方法
}复制代码

One thing to keep in mind using this mode is that the field must be volatileto prevent caching inconsistencies. In fact, Java memory model allows publishers only part of the initialization of an object, which in turn may cause other BUG.

alternative plan

Even after double-checked locking is likely to accelerate the speed, but there are at least two problems:

  • Because it requires the volatile keyword to work properly, so it is not compatible with Java 1.4 and earlier
  • It is very lengthy, making the code difficult to read

For these reasons, let us examine other solutions without these defects. All of the following methods to synchronize tasks JVM.

Early initialization

The easiest way to implement a thread-safe inline objects to create or use an equivalent static blocks. This exploits the fact that: static fields and blocks one after initialization (Java语言规范12.4.2):

public class EarlyInitSingleton {
    private static final EarlyInitSingleton INSTANCE = new EarlyInitSingleton();
    public static EarlyInitSingleton getInstance() {
        return INSTANCE;
    }
     
     // 其他方法
}复制代码

Initialization on demand

Further, since the period is known from the specification with reference to the Java language, the class initialization occurs when we first use of one of the method or field, so we can use nested static class initialization delay to implement:

public class InitOnDemandSingleton {
    private static class InstanceHolder {
        private static final InitOnDemandSingleton INSTANCE = new InitOnDemandSingleton();
    }
    public static InitOnDemandSingleton getInstance() {
        return InstanceHolder.INSTANCE;
    }
 
      // 其他方法
}复制代码

In this case, the InstanceHolderclass will be our first time by calling the getInstanceallocated time to access the field.

enumerate

Finally, a solution instead of using enumeration class. At the time of this writing it is considered to be a single case of the most simple and safest method:

public enum EnumSingleton {
    INSTANCE;
 
     // 其他方法
}复制代码

to sum up

All in all, this article describes the double-checking the lock mode, its limitations and a number of alternative methods. In practice, the excessive verbosity and lack of backward compatibility mode to make this easy to make mistakes, so we should avoid this situation. Instead, we should consider using let JVMbe an alternative synchronization.

  • Solemnly declare : The article first appeared in public No. "FunTester", prohibit third parties (except Tencent cloud) reproduce, publish.

Technology Featured articles

Non-technical Selected Articles

Guess you like

Origin juejin.im/post/5e4753a1e51d4527223e4a20