Home > Java > Java Tutorial > body text

Detailed introduction to singleton mode in concurrency (with code)

不言
Release: 2019-04-13 11:59:25
forward
2474 people have browsed it

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.

The object creation process that consumes the most memory must be constrained. As a creational mode, the singleton mode (Singleton) always maintains that there is only one and only one instance of a certain instance in the application, which can be very obvious. Significantly improve program performance.

The following will discuss the four implementation methods of singleton.
 单线程下的Singleton的稳定性是极好的,可分为两大类:
Copy after login

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;
    }
Copy after login

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;
    }
Copy after login

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;

1. First, let’s solve the synchronization problem: Why does the synchronization exception occur? Let’s use a classic example as an explanation:
There is thread A and thread B calls getLazySingleton() at the same time to obtain the instance. When A calls it, it determines that the instance is null. When preparing to initialize, suddenly thread A was suspended. At this time, the object was not instantiated successfully. Worse happened later. Thread B was run, and it also judged that instance was null. At this time, both A and B entered the instantiation stage, which resulted in Two instances are created, violating the singleton principle.

How to rescue?
As a Java developer, I am certainly no stranger to synchronized. 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;
    }
Copy after login

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;
    }
}
Copy after login

The above source code is the classic volatile 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

Following Moore's Law, the read and write speed of memory is far from satisfying the CPU, so modern Computers have introduced a mechanism to add a cache to the CPU. The cache pre-reads the memory value and temporarily stores it in the cache. Through calculation, the corresponding value in the memory is updated.

**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.3

Another function of volatile is also related to the JVM, that is, the JVM will use its own judgment to rearrange the execution order of the source code to 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.DoubleCheck

This 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;
    }
}
Copy after login

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!

source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!