Table of Contents
1. The concept of lock in Java
2. Synchronized keyword synchronized features
1. Lock elimination example
2. Lock coarsening example
3. Principle of synchronized keyword
1. About Mark Word
2. Lock status changes
(1) No lock→ Lightweight lock
(4) Complete lock upgrade process
Home Java javaTutorial Java keyword synchronized principle and lock status example analysis

Java keyword synchronized principle and lock status example analysis

May 11, 2023 pm 03:25 PM
java synchronized

1. The concept of lock in Java

  • Spin lock: means that when a thread acquires the lock, if the lock has been acquired by other threads, then the thread will wait in a loop , and then continuously determine whether the lock can be successfully acquired, and the loop will not exit until the lock is acquired.

  • Optimistic locking: Assuming there is no conflict, if the data is found to be inconsistent with the previously obtained data when modifying the data, read the latest data and retry the modification.

  • Pessimistic lock: Assuming that a concurrency conflict will occur, synchronize all data-related operations, and start locking from the time the data is read.

  • Exclusive lock (write): Add a write lock to the resource. The thread can modify the resource, but other threads cannot lock it again (single write).

  • Shared lock (read): After adding a read lock to a resource, it can only be read but not modified. Other threads can only add read locks and cannot add write locks (multiple). Just think of it as a Semaphore (semaphore).

  • Reentrant lock & non-reentrant lock: After a thread obtains a lock, it can freely enter other code synchronized by the same lock.

  • Fair lock & unfair lock: The order of competing for locks, if it is first come, first served, is fair. That is to say, it is a fair lock if the order of grabbing the lock and the order of grabbing the lock are guaranteed to be the same.

2. Synchronized keyword synchronized features

Features: reentrant, exclusive, pessimistic lock.

Lock-related optimization:

  • Lock elimination: The parameters to enable lock elimination are -XX: DoEscapeAnalysis, -XX: EliminateLocks .

  • Lock coarsening: JDK has optimized lock coarsening, but we can optimize it from the code level.

1. Lock elimination example

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

/**

 * 锁消除示例,JIT即时编译,进行了锁消除

 * @author 刘亚楼

 * @date 2020/1/16

 */

public class LockEliminationExample {

    /**

     * StringBuilder线程不安全,StringBuffer用了synchronized关键字,是线程安全的

     * 针对下面这种单线程加锁、解锁操作,JIT会进行优化,进行锁消除

     */

    public static void eliminateLock() {

        StringBuffer stringBuffer = new StringBuffer();

        stringBuffer.append("a");

        stringBuffer.append("b");

        stringBuffer.append("c");

        stringBuffer.append("a");

        stringBuffer.append("b");

        stringBuffer.append("c");

        stringBuffer.append("a");

        stringBuffer.append("b");

        stringBuffer.append("c");

    }

}

Copy after login

2. Lock coarsening example

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

/**

 * 锁粗化示例

 * @author 刘亚楼

 * @date 2020/1/16

 */

public class LockCoarseningExample {

    /**

     * 针对下面这种无意义的加锁操作,JIT会进行优化,对变量i的所有操作放到一个同步代码块里

     */

    public static void lockCoarsening() {

        int i = 0;

        synchronized (LockCoarseningExample.class) {

            i++;

        }

        synchronized (LockCoarseningExample.class) {

            i--;

        }

        synchronized (LockCoarseningExample.class) {

            i++;

        }

        synchronized (LockCoarseningExample.class) {

            i++;

            i--;

            i++;

        }

    }

}

Copy after login

Note: The difference between lock elimination and lock coarsening is lock elimination It is optimized for repeated adding and unlocking of a single thread, and ultimately no lock exists. Lock coarsening is not only for single threads, but ultimately there are locks.

3. Principle of synchronized keyword

1. About Mark Word

First of all, the object in the heap consists of object header, instance data and alignment padding.

The object header contains two parts of information. The first part is used to store the runtime data of the object itself, such as hash code, GC generation age, lock status flag, lock held by the thread, bias lock id, etc. This part of the data is officially called "Mark Word".

The other part of the object header is the type pointer, which is the pointer of the object to its class metadata. The virtual machine uses this pointer to determine which class the object is an instance of.

The lock implemented by synchronized is achieved by changing the "Mark Word" of the object header.

"Mard Word" is 32-bit and 64-bit in 32-bit and 64-bit virtual machines (compressed pointers are not turned on) respectively. The 32-bit virtual machine "Mark Word" is as follows:

Java keyword synchronized principle and lock status example analysis

2. Lock status changes

(1) No lock→ Lightweight lock

When lock-free becomes lightweight lock, multiple threads will read the lock-free status mark word content of the object header of the object, and then perform cas operations to modify it. The expected value is lock-free Status mark word content. The new value is the lightweight lock status mark word content. If the modification is successful, Lock record address points to the Lock Record of the thread that successfully acquired the lock.

The demonstration process is as follows:

Java keyword synchronized principle and lock status example analysis

##(2) Lightweight lock→ Heavyweight lock
Due to the thread that failed to acquire the lock successfully It will spin. Long-term spin will consume CPU resources. Therefore, if it spins for a certain number of times, the lock will be upgraded from a lightweight lock to a heavyweight lock.

Heavyweight locks are implemented through object monitors, which include entryList (lock pool), owner (lock holder), waitSet (wait set), etc.

When upgrading to a heavyweight lock, the content of the object header mark word is the monitor address (object monitor address), pointing to the object monitor.

The demonstration process is as follows:

Java keyword synchronized principle and lock status example analysis

Note: The thread that fails to grab the lock will enter the entryList (lock pool). After calling the wait method, the thread will enter the waitSet( Wait set), the thread in waitSet will re-enter entryList after being awakened.

(3) About bias lock
No unlocking after locking, for single thread

The so-called bias is eccentricity, after single thread locks, it will no longer unlock, which reduces Lock→Business processing→Release lock→Lock operation process.

After JDK6, the biased lock optimization has been enabled by default. The biased lock can be disabled through the JVM parameter

-XX:-UseBiasedLocking. If the biased lock is enabled, only one thread will grab the lock. You can Obtain bias lock.

Regarding the bias lock Mark Word, the content is as follows:

Java keyword synchronized principle and lock status example analysis

The bias mark is useful for the first time, but becomes useless after contention occurs.

The essence of biased lock is that it is lock-free. If no multi-threads compete for locks, the JVM considers it to be a single thread and no synchronization is required.

Note: In order to reduce the work of the JVM, synchronization is implemented by many operations at the bottom of the JVM. If there is no contention, there is no need to perform synchronization operations.

(4) Complete lock upgrade process

If the bias lock is not turned on, the lock-free state will be upgraded to a lightweight lock first, and the lightweight lock will be upgraded to a heavyweight if it is selected to a certain extent. Lock.

If the biased lock is turned on, there are two situations:

  • When the lock is not occupied, it will be upgraded to no lock, and then it will be upgraded to lightweight The lock is upgraded from a lightweight lock to a heavyweight lock.

  • When the lock is occupied, it will be upgraded to a lightweight lock, and then upgraded from a lightweight lock to a heavyweight lock.

Java keyword synchronized principle and lock status example analysis

The above is the detailed content of Java keyword synchronized principle and lock status example analysis. 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)

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

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: 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

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