Table of Contents
synchronized
What are user mode and kernel mode?
Why are we divided into kernel mode and user mode?
Lock expansion
Biased lock
Biased lock execution process
Advantages of biased locks
Mark Word Extended Knowledge: Memory Layout
Lightweight lock
Notes
Heavyweight lock
Home Java javaTutorial How to implement the synchronized lock expansion mechanism in Java

How to implement the synchronized lock expansion mechanism in Java

Apr 28, 2023 pm 05:13 PM
java synchronized

    synchronized

    In JDK 1.5, synchronized needs to call the monitor lock (Monitor) to implement, and the monitor lock essentially depends on the underlying layer. It is implemented by the operating system's Mutex Lock (mutex lock). When releasing and acquiring the mutex lock, it needs to be converted from user mode to kernel mode, which causes high costs and requires a long execution time. This kind of lock that relies on the operating system's Mutex Lock implementation is called a "heavyweight lock".

    What are user mode and kernel mode?

    User Mode: When the process is executing the user's own code, it is said to be in the user running state. Kernel Mode: When a task (process) executes a system call and is trapped in the kernel code, we say that the process is in the kernel running state. At this time, the processor is executing in the kernel code with the highest privilege level.

    How to implement the synchronized lock expansion mechanism in Java

    Why are we divided into kernel mode and user mode?

    Assuming that there is no distinction between kernel mode and user mode, the program can read and write hardware resources at will, such as reading, writing and allocating memory at will. In this way, if the programmer accidentally writes inappropriate content to where it should not be Where written, it is likely to cause the system to crash.

    With the distinction between user mode and kernel mode, the program will perform a series of verifications and inspections when performing an operation. Only after confirming that there is no problem can it operate the resources normally, so that it will not Worry about accidentally damaging the system, that is, The distinction between kernel mode and user mode can make the program run more safely, but at the same time, switching between the two modes will cause a certain performance overhead.

    Lock expansion

    In JDK 1.6, in order to solve the performance consumption caused by acquiring and releasing locks, the states of "biased lock" and "lightweight lock" were introduced , at this time, there are a total of 4 synchronized states:

    • No lock

    • Biased lock

    • Lightweight lock

    • Heavyweight lock

    The level of the lock is upgraded in the order mentioned above. Let’s upgrade this The process is called "lock expansion".

    How to implement the synchronized lock expansion mechanism in Java

    PS: So far, the lock upgrade is one-way, that is to say, it can only be upgraded from low to high (no lock-> ; Bias lock-> lightweight lock-> heavyweight lock), there will be no lock degradation.

    Why can lock expansion optimize the performance of synchronized? When we understand these lock states, we will naturally have the answer. Let's take a look at it together.

    Biased lock

    HotSpot The author found through research and practice that in most cases, there is no multi-thread competition for locks, and they are always acquired multiple times by the same thread. In order to allow threads to obtain the lock The cost was lower, so bias locks were introduced.

    Biased Locking means that it will be biased towards the first thread to access the lock. If only one thread accesses the synchronization lock during operation, there will be no multi-thread contention. Then the thread does not need to trigger synchronization. In this case, a bias lock will be added to the thread.

    Biased lock execution process

    When a thread accesses the synchronized code block and acquires the lock, the thread ID of the lock bias will be stored in the Mark Word of the object header, and the thread ID will be stored in the Mark Word of the object header when the thread enters and exits the synchronized block. Instead of locking and unlocking through CAS operations, it detects whether the bias lock pointing to the current thread is stored in Mark Word. If the thread ID in Mark Word is consistent with the accessed thread ID, you can directly enter the synchronization block to code. Execution, if the thread IDs are different, use CAS to try to acquire the lock. If the acquisition is successful, enter the synchronized block to execute the code. Otherwise, the lock status will be upgraded to a lightweight lock.

    Advantages of biased locks

    Biased locks are designed to minimize unnecessary lock switching without multi-thread competition, because the acquisition and release of locks rely on multiple times. CAS atomic instruction, and biased lock only needs to execute the CAS atomic instruction once when replacing the thread ID.

    Mark Word Extended Knowledge: Memory Layout

    In the HotSpot virtual machine, the layout of objects stored in memory can be divided into the following 3 areas:

    • Object Header

    • Instance Data

    • Alignment Filling(Padding)

    The object header also contains:

    • Mark Word (mark field): Our bias lock information is stored in this area.

    • Klass Pointer (Class object pointer)

    The layout of the object in memory is as follows:

    How to implement the synchronized lock expansion mechanism in Java

    In JDK 1.6, biased locking is enabled by default. You can disable biased locking through the "-XX:-UseBiasedLocking=false" command.

    Lightweight lock

    The purpose of introducing lightweight lock is to reduce the use of traditional heavyweight locks in the operating system Mutex Lock (mutex lock) without multi-thread competition. The performance consumption caused by locks. If you use Mutex Lock, each operation of acquiring and releasing a lock will cause switching between user mode and kernel mode, which will cause a huge performance overhead for the system.

    When the bias lock is turned off or multiple threads compete for the bias lock, the bias lock will be upgraded to a lightweight lock. The acquisition and release of the lightweight lock are completed through CAS, and the lock acquisition may be through A certain number of spins to complete.

    Notes

    It needs to be emphasized: Lightweight locks are not used to replace heavyweight locks. Their original intention is to use them without multi-thread competition. , Reduce the performance consumption caused by the use of traditional heavyweight locks. The scenario that lightweight locks adapt to is the situation where threads alternately execute synchronized blocks. If multiple threads access it at the same time, the lightweight lock will expand into a heavyweight lock.

    Heavyweight lock

    synchronized relies on the monitor to implement method synchronization or code block synchronization. Code block synchronization is implemented using the monitorenter and monitorexit instructions. The monitorenter instruction is compiled after Inserted at the beginning of the synchronized code block, while monitorexit is inserted at the end of the method and the exception. Any object has a Monitor associated with it. When a Monitor is held, it will be in a locked state.

    The locking code is as follows:

    public class SynchronizedToMonitorExample {
        public static void main(String[] args) {
            int count = 0;
            synchronized (SynchronizedToMonitorExample.class) {
                for (int i = 0; i < 10; i++) {
                    count++;
                }
            }
            System.out.println(count);
        }
    }
    Copy after login

    When we compile the above code into bytecode, its content is as follows:

    How to implement the synchronized lock expansion mechanism in Java

    It can be seen from the above results that there are multiple monitorenter and monitorexit instructions in the execution of the main method. It can be seen that synchronized is implemented by relying on the Monitor monitor lock, and The monitor lock relies on the operating system's mutex lock (Mutex Lock). Each time the mutex lock is acquired and released, it will switch between user mode and kernel mode, which increases the performance overhead of the system.

    The above is the detailed content of How to implement the synchronized lock expansion mechanism in Java. 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 Article

    Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Nordhold: Fusion System, Explained
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    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)

    Hot Topics

    Java Tutorial
    1664
    14
    PHP Tutorial
    1269
    29
    C# Tutorial
    1249
    24
    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.

    PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

    PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

    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.

    See all articles