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)

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

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

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

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

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