Locks in Java--synchronization locks and locks in the JUC package
This article mainly introduces the relevant information of Java concurrency lock in detail, which has certain reference value. Interested friends can refer to it
According to the time when the lock is added to Java , Locks in Java can be divided into "synchronization locks" and "locks in the JUC package".
Synchronization lock
That is, synchronization is performed through the synchronized keyword to achieve mutually exclusive access to competing resources. Synchronization locks are already supported in Java 1.0.
The principle of synchronization lock is that for each object, there is only one synchronization lock; different threads can jointly access the synchronization lock. However, at the same point in time, the synchronization lock can and can only be acquired by one thread. In this way, the thread that has obtained the synchronization lock can be scheduled by the CPU and executed on the CPU; while the thread that has not obtained the synchronization lock must wait until it obtains the synchronization lock before it can continue to run. This is the principle of multi-thread synchronization through synchronization lock!
The lock in the JUC package
Compared with the synchronization lock, the function of the lock in the JUC package is more powerful. It provides a Framework, this framework allows for more flexible use of locks, but its usage is more difficult.
The locks in the JUC package include: Lock interface, ReadWriteLock interface, LockSupport blocking primitive, Condition condition, AbstractOwnableSynchronizer/AbstractQueuedSynchronizer/AbstractQueuedLongSynchronizer three Abstract classes, ReentrantLock exclusive lock, ReentrantReadWriteLock read-write lock. Since CountDownLatch, CyclicBarrier and Semaphore are also implemented through AQS; therefore, I will also introduce them into the lock framework.
First, look at the frame diagram of the lock, as shown below.
01. Lock interface
The Lock interface in the JUC package supports those with different semantics (Reentrancy, fairness, etc.) locking rules. The so-called different semantics means that locks can include "fair mechanism locks", "unfair mechanism locks", "reentrant locks" and so on. "Fair mechanism" refers to "the mechanism for different threads to acquire locks is fair", while "unfair mechanism" refers to "the mechanism for different threads to acquire locks is unfair", and "reentrant lock" refers to the same Locks can be acquired multiple times by a thread.
02. ReadWriteLock
The ReadWriteLock interface defines some readers that can be shared in a similar way to Lock. Writer-exclusive lock. Only one class in the JUC package implements this interface, ReentrantReadWriteLock, as it is suitable for most standard usage contexts. But programmers can create their own implementations suitable for non-standard requirements.
03. AbstractOwnableSynchronizer/AbstractQueuedSynchronizer/AbstractQueuedLongSynchronizer
04. LockSupport
05. Condition
Condition needs to be used in conjunction with Lock. Its function is to replace the Object monitor method. It can sleep/wake up threads through await() and signal().
The Condition interface describes the conditions Variables that may be associated with the lock. These variables are similar in usage to implicit monitors accessed using Object.wait, but provide more powerful functionality. It is important to note that a single Lock may be associated with multiple Condition objects. To avoid compatibility issues, Condition method names are different from those in the corresponding Object version.
06. ReentrantLock
## (01) ReentrantLock implements the Lock interface.
(03) There are "fair lock class" FairSync and "unfair lock class" NonfairSync in ReentrantLock, which are both subclasses of Sync. The sync object in ReentrantReadWriteLock is one of FairSync and NonfairSync. This also means that ReentrantLock is one of "fair lock" or "unfair lock". ReentrantLock is an unfair lock by default.
07. ReentrantReadWriteLock
## ReentrantReadWriteLock is the implementation class of the read-write lock interface ReadWriteLock, which includes the subclasses ReadLock and WriteLock. ReentrantLock is a shared lock, while WriteLock is an exclusive lock.
The UML class diagram of ReentrantReadWriteLock is as follows:
(01) ReentrantReadWriteLock implements the ReadWriteLock interface.
(02) ReentrantReadWriteLock contains sync object, read lock readerLock and write lock writerLock. Both the read lock ReadLock and the write lock WriteLock implement the Lock interface.
CountDownLatch is a synchronization auxiliary class that completes a set of operations that are being executed in other threads. It allows one or more threads to wait forever. The UML class diagram of CountDownLatch is as follows:
CountDownLatch contains the sync object, and sync is the Sync type. CountDownLatch's Sync is an instance class, which inherits from AQS.
## CyclicBarrier is a synchronization auxiliary class that allows a group of threads to wait for each other until a certain A common barrier point. Because this barrier can be reused after the waiting thread is released, it is called a loop barrier.
CyclicBarrier includes "ReentrantLock object lock" and "Condition object trip". It is implemented through exclusive locks. The difference between CyclicBarrier and CountDownLatch is:
(01) The function of CountDownLatch is to allow 1 or N threads to wait for other threads to complete execution; while CyclicBarrier allows N threads to wait for each other.
10. Semaphore
## Semaphore is a counting semaphore, and its essence is a "shared lock".
The semaphore maintains a semaphore permission set. The thread can obtain the permission of the semaphore by calling acquire(); when there is an available permission in the semaphore, the thread can obtain the permission; otherwise, the thread must wait until there is an available permission. A thread can release the semaphore license it holds through release().
The UML class diagram of Semaphore is as follows:
Like "ReentrantLock", Semaphore contains sync objects, sync is a Sync type; and, Sync is also a Abstract class inherited from AQS. Sync also includes "fair semaphore" FairSync and "unfair semaphore" NonfairSync.
The above is the detailed content of Locks in Java--synchronization locks and locks in the JUC package. 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

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

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

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