Java Concurrency: Introduction and principle analysis of Abstractqueuedsynchronizer __ Multithreading

Source: Internet
Author: User
This article belongs to the Java Concurrent Series, the original address: http://ifeve.com/introduce-abstractqueuedsynchronizer/Concurrent Programming Network has the original text, rough to see again, many places do not understand. Today in See Juc lock part, the bottom or rely on AQS implementation, deliberately on the basis of the original comb. The original text reads as follows: Brief IntroductionProvides a basic framework based on FIFO queues that can be used to build locks or other related synchronization devices. The Synchronizer (hereinafter referred to as a Synchronizer) uses an int to represent the state, expecting it to be the basis for achieving most of the synchronization requirements. The method used is inheritance, and the subclass manages its state by inheriting the Synchronizer and the way it is implemented, by manipulating the state in a way that resembles acquire and release. However, the manipulation of state in a multithreaded environment must ensure atomicity, so the subclass's grasp of state requires the following three methods provided by this Synchronizer to operate the state:
Java.util.concurrent.locks.AbstractQueuedSynchronizer.getState () java.util.concurrent.locks.AbstractQueuedSynchronizer.setState (int) The java.util.concurrent.locks.AbstractQueuedSynchronizer.compareAndSetState (int, int) Subclass recommendation is defined as the inner class of the custom Synchronizer, The Synchronizer itself does not implement any synchronization interfaces, it simply defines a number of acquire methods for use. The Synchronizer can be either an exclusive or a shared mode, and when it is defined as an exclusive mode, the acquisition of other threads is blocked, and the shared schema succeeds for multiple thread fetches.
Synchronizer is the key to implement the lock, using the Synchronizer to implement the semantics of the lock, and then aggregating the Synchronizer in the implementation of the lock. It can be understood that the lock API is user-oriented, it defines the public behavior that interacts with the lock, and each lock requires a specific operation to be done through these behaviors (for example: Two threads can be allowed to lock up, excluding more than two threads), but the implementation is based on the Synchronizer to complete The Synchronizer is oriented to thread access and resource control, which defines how the thread is able to acquire the resources and queue the threads. The lock and Synchronizer are well insulated from the areas in which they need to be concerned, and, strictly speaking, the Synchronizer can be applied to other synchronization facilities (including locks) other than locks.
From the user's perspective, the AQS function can be divided into two categories: exclusive and shared, all of its subclasses, either implementing and using its proprietary APIs, or using shared-lock functionality, rather than using two sets of APIs at the same time. Even its most famous subclass Reentrantreadwritelock, also through two internal classes: Read lock and Write lock, implemented by two sets of APIs, we only need to understand that AQS has exclusive control and shared control functions.
The beginning of the Synchronizer mentions that its implementation relies on a FIFO queue, then the element node in the queue is the container that holds the thread reference and thread state, and each thread's access to the Synchronizer can be viewed as a node in the queue. Node's main include the following member variables:
Node {
    int waitstatus;
    Node prev;
    Node Next;
    Node Nextwaiter;
    thread thread;
}
The above five member variables are primarily responsible for saving the thread references of the node, synchronizing the predecessor and successor nodes of the wait queue (hereinafter referred to as the sync queue), and also including the synchronization state.
Property name Describe
int Waitstatus Represents the state of a node. The states that are included are:

Cancelled, a value of 1, indicates that the current thread is canceled; SIGNAL, the value is-1, indicating that the successor node of the current node contains a thread that needs to be run, that is, Unpark CONDITION, and the value is-2, indicating that the current node is waiting for CONDITION. That is, in the condition queue; PROPAGATE, the value is-3, which indicates that subsequent acquireshared in the current scene can be executed; A value of 0 indicates that the current node is in the sync queue, waiting for the lock to be acquired.

Node prev The predecessor nodes, such as the current node being canceled, require the predecessor and successor nodes to complete the connection.
Node Next Successor node.
Node Nextwaiter Stores the successor node in the condition queue.
Thread thread The current thread when entering the queue.
The node becomes the basis for the sync queue and the condition queue build, and the sync queue is included in the Synchronizer. The Synchronizer has three member variables: the head node heads of the sync queue, the tail nodes of the sync queue tail, and the status state. For the acquisition of a lock, the request forms a node, mounts it on the tail, and the transfer of the lock resource (release and fetch) is done backwards from the head. For state states that are maintained by the Synchronizer, the acquisition of multiple threads will result in a chain-structured structure.
API Description

When implementing a custom Synchronizer, you need to manipulate state changes using the GetState (), SetState (), and Compareandsetstate () methods provided by the Synchronizer.

Method name Describe
protected Boolean tryacquire (int arg) Platoon it's getting this state. The implementation of this method requires querying whether the current state is allowed to be fetched, and then fetching (using Compareandsetstate) state.
protected Boolean tryrelease (int arg) Release state.
protected int tryacquireshared (int arg) Gets the status in the shared mode.
protected Boolean tryreleaseshared (int arg) Free State in shared mode.
Protected Boolean isheldexclusively () In exclusive mode, the state is occupied.

Implementing these methods must be non-blocking and thread-safe, and it is recommended that you use the Synchronizer's parent class Java.util.concurrent.locks.AbstractOwnableSynchronizer to set the current thread.
Beginning with the reference to a FIFO queue within the Synchronizer, the following pseudo code can be expressed for the acquisition and release of an exclusive lock.
Gets an exclusive lock.

01 while (get Lock) {
02 if (get to) {
03 Exit While Loop
04 } else {
05 if (current thread does not enter queue) {
06 So into the queue
07
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.