Java Multithreading Condition interface principle detailed __java

Source: Internet
Author: User

The condition interface provides an object-like monitor method that can be used in conjunction with lock to implement a wait/notification pattern, but the two are different in terms of usage and functional characteristics.
Condition Interface Detailed

Condition defines two types of methods for waiting/notifying, in which the current thread needs to obtain the lock associated with the condition object in advance when it calls these methods. The condition object is created by the lock object (the Newcondition () method that invoked the lock object), in other words, the condition is dependent on the lock object.

Lock lock = new Reentrantlock ();
    Condition Condition = Lock.newcondition ();
    public void Conditionwait () throws Interruptedexception {
        lock.lock ();
        try {
            condition.await ();
        } finally {
            lock.unlock ();
    }} public void Conditionsignal () throws Interruptedexception {
        lock.lock ();
        try {
            condition.signal ();
        } finally {
            lock.unlock ();
        }
    }

Condition objects are generally used as member variables. When the await () method is invoked, the current thread releases the lock and waits here, while the other threads call the condition object's signal () method, notifying the current thread that the current line Cheng is returned from the await () method and has acquired the lock before returning.

    /** * The current thread enters the wait state until it is notified (signal) or interrupted, the current thread enters the background running state and the await () method returns * The other thread calls the condition signal or Signalall method, and the current thread is selected to wake * 1, other threads (interrupt) interrupts the current thread * 2, if the current waiting thread returns from the await method, indicating that the current thread has acquired the lock/Void await () throws Int of the condition object

    Erruptedexception;

    /** * The current thread enters the wait state until notified, does not respond to the interrupt/void awaituninterruptibly (); /** * <pre> {@code * boolean amethod (long timeout, timeunit unit) {* Long Nanos = Unit.tonanos (ti
     Meout);
     * Lock.lock ();
     * Try {* while (!conditionbeingwaitedfor ()) {* If (Nanos <= 0L) * return false;
     * Nanos = Thecondition.awaitnanos (Nanos);
     *} *//... * lock.unlock (); *}}</pre> * The current thread enters the wait state until it is notified, interrupted, or timed out. The return value represents the time remaining, and if awakened before Nanostimeout nanosecond, then the return value is nanostimeout-actual time-consuming * return value <=0 Description Timeout */Long Awaitnanos (Long NA

    Nostimeout) throws Interruptedexception; /** * Current LineThe process enters the wait state until it is notified, interrupted, or timed out and returns true if it is not notified at a specified time, otherwise return false */Boolean await (long time, Timeunit unit) throws Interruptedexce

    ption; /** * wakes up a thread waiting on the condition that must obtain the lock/void signal associated with condition before returning from the wait method;

The

Gets a condition must pass the lock's Newcondition () method. The following is an example of a bounded queue to get an insight into how condition is used. A bounded queue is a special kind of queue that, when the queue is empty, gets the queue to block the fetch thread until there is a new element in the queue, and when the queue is full, the insertion of the queue blocks the insert thread until the queue appears empty

public class Boundedqueue<t> {private object[] items;

    Added subscript, deleted subscript and array current quantity private int addindex,removeindex,count;

    Private lock lock = new Reentrantlock ();

    Private Condition Notempty = Lock.newcondition ();

    Private Condition Notfull = Lock.newcondition ();
    public boundedqueue (int size) {items = new object[size];
     /** * Add an element, if the array is full, add the thread into the wait state until there is a "vacancy" * @author Fuyuwei * May 21, 2017 afternoon 6:14:55 * @param t
        * @throws interruptedexception/public void Add (T-T) throws interruptedexception{Lock.lock ();
            try{while (count = = items.length) {notfull.await ();
            } Items[addindex] = t;
            if (++addindex = = items.length) Addindex = 0;
            ++count;
        Notempty.signal ();
        }finally{Lock.unlock ();
 }/** * Deletes an element from the head, if the array is empty, the delete thread enters the wait state until there is a new addition element * @author Fuyuwei    * May 21, 2017 afternoon 6:20:54 * @return * @throws interruptedexception/@SuppressWarnings ("unchecked")
        Public T-Remove () throws interruptedexception{Lock.lock ();
            try{while (count = = 0) notempty.await ();
            Object x = Items[removeindex];
            if (++removeindex = = items.length) Removeindex = 0;
            --count;
            Notfull.signal ();
        Return (T) x;
        }finally{Lock.unlock (); }
    }
}

First you need to obtain the lock to ensure the visibility and exclusivity of the array modifications. When the number of arrays equals the length of an array, the expression is full, then notfull.await () is invoked, and the current thread releases the lock and enters the wait state. If the number of arrays is not equal to the array length, indicating that the array is not full, add the element to the array, and notify the thread waiting on the notempty that a new element is already available in the array. Use a while loop instead of an if judgment in addition and deletion methods to prevent premature or accidental notification, which can exit the loop only if the condition is met. Recall the classical paradigm of waiting/notification mentioned earlier, which is very similar to the condition principle Analysis

Conditionobject is the internal class of the Synchronizer Abstractqueuedsynchronizer, because the condition operation needs to acquire the associated lock, so the internal class as the Synchronizer is also more reasonable. Each condition object contains a queue that is key to the condition object's ability to implement wait/notify. The following is an analysis of the implementation of the condition, which includes: Waiting queues, waiting, and notification waiting queues

The wait queue is a FIFO queue in which each node in the queue contains a thread reference, which is the thread that waits on the condition object, and if a thread calls the Condition.await () method, the thread releases the lock, Construct a node to join the wait queue and enter the wait state
A condition contains a wait queue, condition has a first node (firstwaiter) and a tail node (lastwaiter). The current thread calls the Condition.await () method, the node is constructed with the current thread, and the node is added to the wait queue from the tail, waiting for the basic structure of the queue as shown in the following figure

As shown in the figure, condition has a reference to the end of the node, and the new node simply needs to point the original tail node nextwaiter to it, and update the tail node. The above node reference update process does not use the CAS guarantee because the thread that calls the await () method must be the thread that acquired the lock, that is, the process is guaranteed thread-safe by the lock. On the monitor model of object, an object has a synchronous queue and a wait queue, and the lock (or, more specifically, the Synchronizer) in the contract has a synchronization queue and multiple wait queues, and the corresponding relationship is shown in the following illustration
Waiting for

Calling the condition await () method (or a method that starts with await) causes the current thread to enter the wait queue and release the lock while the thread state becomes a waiting state. When returned from the await () method, the current thread must have acquired the condition associated lock. If the await () method is viewed from the perspective of the queue (synchronous queue and wait queue), when the await () method is invoked, the same as the first node of the synchronization queue (the node that acquired the lock) moves to the condition wait queue

public final void await () throws Interruptedexception {if (thread.interrupted ())
        throw new Interruptedexception ();
        The current thread joins the wait queue node node = Addconditionwaiter ();
        Releases the sync state, which is the release lock int savedstate = fullyrelease (node);
        int interruptmode = 0;
            while (!isonsyncqueue (node)) {Locksupport.park (this);
        if ((Interruptmode = checkinterruptwhilewaiting (node))!= 0) break; } if (acquirequeued (node, savedstate) && interruptmode!= throw_ie) Interruptmode = Reinterrup
        T
        if (node.nextwaiter!= null) unlinkcancelledwaiters ();
    if (interruptmode!= 0) reportinterruptafterwait (interruptmode); }

The thread that calls the method succeeds in acquiring the lock thread, the first node in the synchronization queue, which constructs the current thread as a node and joins the wait queue, releases the synchronization state, wakes the successor node in the synchronization queue, and then the current thread enters the wait state. When a node in the wait queue is awakened, the Wake node's thread begins to attempt to get the sync state. If the Condition.signal () method is not invoked through another thread, but instead interrupts the waiting thread, a interruptedexception notification is thrown

Calling the condition signal () method wakes up the node with the longest waiting time in the wait queue (the first node) and moves the node to the synchronization queue before the node is awakened

Public final void signal () {
        if (!isheldexclusively ())
            throw new Illegalmonitorstateexception ();
        Node-i = firstwaiter;
        if (!= null)
            dosignal (a)
    

The precondition for the

Invocation of this method is that the current thread must acquire the lock and see the signal () method for a isheldexclusively () check, that is, the current thread must be the thread that acquired the lock. Then get the first node of the wait queue, move it to the synchronization queue, and use the thread
node in the Locksupport wake node to move from the wait queue to the synchronization queue as shown in the following illustration

by calling the Synchronizer's Enq (node node) method, Wait for the head node thread in the queue to move securely to the synchronization queue. When a node is moved to a synchronization queue, the current thread then uses Locksupport to wake the node's thread. The awakened thread will exit from the while loop in the await () method (the Isonsyncqueue (node node) method returns True, the nodes are already in the synchronization queue), and then invoke the Synchronizer's acquirequeued () Method is added to the competition to get the sync state. After a successful acquisition of the Sync state (or lock), the awakened thread returns from the await () method previously invoked, at which point the thread has successfully acquired the lock. The condition Signalall () method, which is equivalent to performing a signal () method once for each node in the wait queue, is to move all nodes in the wait queue to the synchronization queue and wake up the threads for each node.

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.