Java keyword synchronized principle and lock status example analysis
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 |
|
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 |
|
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:
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:
-XX:-UseBiasedLocking. If the biased lock is enabled, only one thread will grab the lock. You can Obtain bias lock.
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.
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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

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.

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

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.
