Table of Contents
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.
1. First, let’s solve the synchronization problem: Why does the synchronization exception occur? Let’s use a classic example as an explanation: " >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. " >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.
Home Java javaTutorial Detailed introduction to singleton mode in concurrency (with code)

Detailed introduction to singleton mode in concurrency (with code)

Apr 13, 2019 am 11:59 AM
java Singleton pattern Design Patterns

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!

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 admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles