Definition: As an object creation mode, the singleton pattern ensures that a class has only one instance and instantiates itself and provides this instance to the entire system. This class is called a singleton class. The singleton mode is divided into a hungry mode and a lazy mode.

The hungry mode code is as follows:

Write a picture description here

The lazy mode code is as follows:

Write a picture description here

The difference between hungry mode and lazy mode:

Hungry Chinese style is a typical space change time. When the class is loaded, an instance of the class is created. No matter what you use, it is created first, and then each time you call it, you don't need to judge it again, saving running time. Thread safe

Lazy style is a typical time-changing space, that is, each time an instance is obtained, it will be judged to see if it is necessary to create an instance, which wastes the judgment time. Of course, if no one has been used, then no instance will be created, saving memory space. Thread is not safe

How to implement thread safe lazy mode?

Use synchronized

2. Double check and lock

The so-called "double check and lock" mechanism means that not every time you enter the geoTInstance method, you need to synchronize, but not synchronize first. After entering the method, first check whether the instance exists. If it does not exist, the following sync block is executed. This is the first recheck. After entering the sync block, check if the instance exists. If it does not exist, create an instance in the case of synchronization. This is the second check. In this way, only one synchronization is required, thereby reducing the time wasted by making multiple judgments in the case of synchronization. as follows:

Write a picture description here

The implementation of the "double check and lock" mechanism uses the keyword volaTIle, which means that the value of the variable modified by volaTIle will not be cached by the local thread, and all read and write to the variable is directly operated on shared memory. This ensures that multiple threads can handle the variable correctly.

72V Battery pack

72V Battery Pack ,Lithium Ion Battery Pack,Lithium Battery Pack,Battery Power Pack

Zhejiang Casnovo Materials Co., Ltd. , https://www.casnovonewenergy.com