Singleton mode of Telegram open source project

Singleton Pattern of NotificationCenter

public class NotificationCenter {
    private static volatile NotificationCenter Instance = null;

    public static NotificationCenter getInstance() {
        NotificationCenter localInstance = Instance;
        if (localInstance == null) {
            synchronized (NotificationCenter.class) {
            //多线程环境下,之前得到的instance为null,但现在很有可能在锁定NotificationCenter.class之前已经被实例化了,所以需要进一步判断instance是否实例化。
                localInstance = Instance;
                if (localInstance == null) {
                    Instance = localInstance = new NotificationCenter();
                }
            }
        }
        return localInstance;
    }
}

Singleton Pattern Analysis of NotificationCenter

This singleton pattern is a thread-safe singleton pattern with double-checked locks. It is the most efficient and safest way to write

The addition of the volatile keyword to Instance ensures that reordering is prevented in a multi-threaded environment, and the reference obtained when instantiating the NotificationCenter object in a multi-threaded environment is not initialized.

In fact, instantiating an object can be divided into three steps:
  (1) Allocate memory space.
  (2) Initialize the object.
  (3) Assign the address of the memory space to the corresponding reference.
However, since the operating system can reorder the instructions, the above process may also become the following process:
  (1) Allocate memory space.
  (2) Assign the address of the memory space to the corresponding reference.
  (3) Initializing the object
  If it is this process, an uninitialized object reference may be exposed in a multi-threaded environment, resulting in unpredictable results. Therefore, to prevent reordering of this process, we need to set the variable to a variable of type volatile.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325549568&siteId=291194637