This article brings you a detailed introduction to the singleton mode in concurrency (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
单线程下的Singleton的稳定性是极好的,可分为两大类:
1.Eager (Hungry type): Create an object immediately when the class is loaded.
public class EagerSingleton { //1. 类加载时就立即产生实例对象,通过设置静态变量被外界获取 //2. 并使用private保证封装安全性 private static EagerSingleton eagerSingleton = new EagerSingleton(); //3. 通过构造方法的私有化,不允许外部直接创建对象,确保单例的安全性 private EagerSingleton(){ } public static EagerSingleton getEagerSingleton(){ return eagerSingleton; }
2. Lazy (lazy type): The object is not created immediately when the class is loaded, and is not instantiated until the first user obtains it.
public class LazySingleton { //1. 类加载时并没有创建唯一实例 private static LazySingleton lazySingleton; private LazySingleton() { } //2、提供一个获取实例的静态方法 public static LazySingleton getLazySingleton() { if (lazySingleton == null) { lazySingleton = new LazySingleton(); } return lazySingleton; }
In terms of performance, LazySingleton is obviously better than EagerSingleton. If the loading of classes requires a lot of resources (e.g. reading large file information), then the advantages of LazySingleton are obvious. But by reading the code, it's easy to spot a fatal problem.How to maintain security among multiple threads?
The multi-thread concurrency problem will be analyzed below:
The key to solving this problem lies in two aspects: 1. Synchronization; 2. Performance;
How to rescue?
As a Java developer, I am certainly no stranger tosynchronized. When it comes to multi-threading, most people think of him (after JDK6, his performance has been greatly improved and the solution is simple. Concurrency, very applicable).
Then let us use synchronized to try to solve it:
//由synchronized进行同步加锁 public synchronized static LazySingleton getLazySingleton() { if (lazySingleton == null) { lazySingleton = new LazySingleton(); } return lazySingleton; }
The synchronization problem seems to be solved, but as a developer, the most important thing is to ensure performance, use synchronized There are advantages and disadvantages. Due to the locking operation, the code segment is pessimistically locked. Only when one request is completed can the next request be executed. Usually code pieces with the synchronized keyword will be several times slower than code of the same magnitude, which is something we don't want to see. So how to avoid this problem? There is this suggestion in Java's definition of synchronized: the later you use synchronized, the better the performance (refined locking).
2. Therefore, we need to start solving the performance problem. Optimize according to synchronized:
public class DoubleCheckLockSingleton { //使用volatile保证每次取值不是从缓存中取,而是从真正对应的内存地址中取.(下文解释) private static volatile DoubleCheckLockSingleton doubleCheckLockSingleton; private DoubleCheckLockSingleton(){ } public static DoubleCheckLockSingleton getDoubleCheckLockSingleton(){ //配置双重检查锁(下文解释) if(doubleCheckLockSingleton == null){ synchronized (DoubleCheckLockSingleton.class) { if(doubleCheckLockSingleton == null){ doubleCheckLockSingleton = new DoubleCheckLockSingleton(); } } } return doubleCheckLockSingleton; } }
The above source code is the classicvolatile keyword (reborn after JDK1.5) Double Check Lock (DoubleCheck), optimized to the greatest extent The performance overhead caused by sychronized. Volatile and DoubleCheck will be explained below.
1.volatile
was officially implemented and used after JDK1.5. Previous versions only defined this keyword without specific implementation. If you want to understand volatile, you must have some understanding of the JVM's own memory management:
1.1
**1.2** The JVM imitates the PC's approach and divides its own **working memory** in the memory. This part of the memory functions the same as the cache, which significantly improves the JVM work. Efficiency, but everything has pros and cons. This approach also causes transmission problems when the working memory communicates with other memories. One function of volatile is to force the latest value to be read from memory to avoid inconsistency between cache and memory.
1.3Another function of volatile is also related to the JVM, that is, the JVM will use its own judgment to rearrange the execution order of thesource codeto ensure that the instructions Pipeline coherence to achieve the optimal execution plan. This approach improves performance, but it will produce unexpected results for DoubleCheck, and the two threads may interfere with each other. Volatile provides a happens-before guarantee (writing takes priority over reading), so that the object is not disturbed and ensures safe stability.
2.DoubleCheckThis is a legacy of modern programming. It is assumed that after entering the synchronized block, the object has been instantiated, and the judgment needs to be made again.
Of course there is also a
officially recommended singleton implementation method###: ######Since the construction of the class is already atomic in the definition, the above-mentioned problems are solved. It will not be generated again. It is a good singleton implementation method and is recommended. ###//使用内部类进行单例构造 public class NestedClassSingleton { private NestedClassSingleton(){ } private static class SingletonHolder{ private static final NestedClassSingleton nestedClassSingleton = new NestedClassSingleton(); } public static NestedClassSingleton getNestedClassSingleton(){ return SingletonHolder.nestedClassSingleton; } }
The above is the detailed content of Detailed introduction to singleton mode in concurrency (with code). For more information, please follow other related articles on the PHP Chinese website!