Home Java javaTutorial Locks in Java--synchronization locks and locks in the JUC package

Locks in Java--synchronization locks and locks in the JUC package

Jun 17, 2017 pm 02:18 PM
java Synchronize

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

## AbstractQueuedSynchronizer is a class called AQS. It is a A very useful superclass that can be used to define locks and other synchronizers that rely on queuing and blocking threads; classes such as ReentrantLock, ReentrantReadWriteLock, CountDownLatch, CyclicBarrier and Semaphore are all implemented based on the AQS class. The AbstractQueuedLongSynchronizer class provides the same functionality but extends support for 64-bit synchronization state. Both extend the class AbstractOwnableSynchronizer (a simple class that helps keep track of which thread currently maintains exclusive synchronization).

04. LockSupport

LockSupport provides "create locks" and "basic thread blocking primitives for other synchronization classes".


The function of LockSupport is somewhat similar to "Thread.suspend() and Thread.resume() in Thread". The functions of park() and unpark() in LockSupport are to block threads and release them respectively. Block the thread. However, park() and unpark() will not encounter the problem of "deadlock that may be caused by Thread.suspend and Thread.resume".


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

## ReentrantLock is an exclusive lock. The so-called exclusive lock refers to a lock that can only be occupied by itself, that is, it can only be acquired by one thread lock at the same point in time. ReentrantLock locks include "fair ReentrantLock" and "unfair ReentrantLock". "Fair ReentrantLock" means "the mechanism for different threads to acquire locks is fair", while "unfair ReentrantLock" means "the mechanism for different threads to acquire locks is unfair", and ReentrantLock is a "reentrant lock" .


The UML class diagram of ReentrantLock is as follows:

##  (01) ReentrantLock implements the Lock interface.

 (02) There is a member variable sync in ReentrantLock, sync is the Sync type; Sync is an abstract class, and it inherits from AQS.

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

 (03) Like "ReentrantLock", sync is a Sync type; moreover, Sync is also an abstract class inherited from AQS. Sync also includes "fair lock" FairSync and "unfair lock" NonfairSync.



08. CountDownLatch


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.


09. CyclicBarrier

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

The UML class diagram of CyclicBarrier is as follows:


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.

 (02) The counter of CountDownLatch cannot be reset; the counter of CyclicBarrier can be reset and used, so it is called a cyclic barrier.





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!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 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)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

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

See all articles