Condition in Java

Source: Internet
Author: User

I. Overview

The interface is located in the Java.util.concurrent.locks
Disclaimer: Publicinterface Condition

ConditionThe Object monitor methods ( wait , notify and notifyAll ) are decomposed into distinct objects to Lock provide multiple wait sets (Wait-set) for each object by combining these objects with any implementation. This replaces the use of Lock synchronized methods and statements, Condition replacing the use of the Object monitor method.

A condition (also known as a conditional queue or condition variable ) provides a means for a thread to suspend the thread (that is, let it "wait") until another thread that a state condition might now be true notifies it. Because access to this shared state information occurs in different threads, it must be protected so that a form of lock is associated with that condition. The primary property for waiting to provide a condition is to atomically release the associated lock and suspend the current thread as if it were Object.wait done.

ConditionAn instance is essentially bound to a lock. To obtain an instance for a specific Lock instance Condition , use its newCondition() method.

As an example, assume that there is a binding buffer that it supports put and take methods. If an attempt is made to perform an operation on an empty buffer, the take thread will block until an item becomes available, and if an attempt is made to perform an operation on a full buffer, the put thread will block until the space becomes available. We like to save threads and threads in a separate wait set put take , so that you can take advantage of the best planning when an item or space in the buffer becomes available, notifying only one thread at a time. You can use two Condition instances to do this.

class   Boundedbuffer {Final Lock lock = new Reentrantlock ();    Final Condition notfull = Lock.newcondition ();    Final Condition notempty = Lock.newcondition ();   Final object[] items = new OBJECT[100];   int Putptr, takeptr, Count;     public void put (Object x) throws Interruptedexception {Lock.lock ();       try {while (count = = items.length) notfull.await ();        ITEMS[PUTPTR] = x;       if (++putptr = = items.length) putptr = 0;       ++count;     Notempty.signal ();     } finally {Lock.unlock ();     }} public Object take () throws Interruptedexception {Lock.lock ();       try {while (count = = 0) notempty.await ();        Object x = items[takeptr];       if (++takeptr = = items.length) takeptr = 0;       --count;       Notfull.signal ();     return x;     } finally {Lock.unlock (); }   }  }


ArrayBlockingQueueclass provides this functionality, so there is no reason to implement this example class. )

ConditionImplementations can provide Object behavior and semantics that differ from the monitor method, such as a guaranteed sort of notification, or a lock that does not need to be maintained when the notification is executed. If an implementation provides such a special semantics, the implementation must record these semantics.

Note that the Condition instances are just plain objects that themselves can be used as synchronized targets in the statement, and can invoke their own wait and notification monitor methods. Gets Condition The monitor lock for an instance or uses its monitor method, with no specific relationship to getting and the Condition related Lock or using its waiting and signalling methods. To avoid confusion, it is recommended that you do not use instances in this way except in their own implementations Condition .

Unless otherwise noted, passing a value for any parameter null will result in a throw NullPointerException .

Implementation considerations

When waiting Condition , " spurious wakeup " is allowed, which usually serves as a concession to the underlying platform semantics. For most applications, this has a small practical impact because it Condition should always be waiting in a loop and testing the status declaration that is waiting. An implementation is free to remove possible spurious wakes, but it is recommended that application programmers always assume that these spurious wakes can occur and therefore always wait in a loop.

Three forms of conditional wait (interruptible, non-disruptive, and timed out) implementations on some platforms and their performance characteristics may vary. In particular, it may be difficult to provide these features and maintain specific semantics, such as ordering guarantees. Further, the ability to actually suspend the interrupt process is not always feasible on all platforms.

Therefore, an implementation is not required to define exactly the same guarantees or semantics for all three forms of waiting, nor does it require the actual suspension of the thread to be supported.

Requires implementation to clearly document the semantics and guarantees provided by each wait method, which must conform to the interrupt semantics defined in this interface when an implementation does not support the suspend of a thread.

Since interrupts usually mean cancellation, and often very little interruption checking, implementations can respond to interrupts before the return of the normal method. This is true even if the interrupt that occurs after another operation may release the lock. The implementation should log this behavior.


Ii. details of the method

1. void await () throwsinterruptedexception causes the current thread to wait until it receives a signal or is interrupted.

The

Lock associated with this Condition is freed atomically, and the current thread is disabled for thread scheduling purposes, and the current thread will remain dormant until one of the following four conditions :

    li> Another thread calls the signal () method of this Condition , and it happens that the current thread is selected as a wake-up thread, or
  • another thread calls this Condition 's Signalall () method, or
  • another thread that interrupts the current thread and supports the suspend of a thread, or
  • occurs false wake

In all cases, the lock that is related to this condition must be retrieved before this method can return the current thread. When a thread returns, you can guarantee that it remains this lock.

If the current thread:

  • has set the interrupt state of the thread when it enters this method, or
  • is interrupted while the support waits and threads are suspended,
throws Interru Ptedexception and clears the interrupt state of the current thread. In the first case, you do not specify whether the break test occurs before the lock is released.

Implementation Considerations

The

assumes that the current thread maintains a lock associated with this Condition when this method is called. This depends on the implementation to determine if this is the case and how to respond to it. Typically, an exception is thrown (such as illegalmonitorstateexception ) and the implementation must record it.

The implementation may prefer to respond to an interrupt than the normal method returned in response to a signal. In this case, the implementation must ensure that the signal is redirected to another waiting thread, if any.

Thrown:
InterruptedException -If the current thread is interrupted (and the support is suspended)
2. void awaituninterruptibly () causes the current thread to be in a wait state until the signal is received.

The lock associated with this condition is freed atomically, and the current thread is disabled for the purpose of thread scheduling, and the current thread will remain dormant until one of the following three situations occurs:

    • One of the other threads calls this Condition signal() method, and it happens that the current thread is selected as a wake-up thread;
    • One of the other threads calls this Condition signalAll() method;
    • " false Wakeup " occurred.

In all cases, the lock associated with this condition must be re-acquired before this method can return the current thread. When a thread returns, it is guaranteed to hold the lock.

If the interrupt state of the current thread is set when entering this method, or if the thread is interrupted while waiting, it will continue to wait until the signal is received. When it is eventually returned from this method, its break state will still be set.

Implementation Considerations

Assuming that this method is called, the current thread maintains a Condition lock associated with this. This depends on the implementation to determine if this is the case and how to respond to it. Typically, an exception is thrown (for example IllegalMonitorStateException ) and the implementation must record it.


3. Long Awaitnanos (long Nanostimeout) throws Interruptedexception causes the current thread to wait until it receives a signal, is interrupted, or arrives at a specified wait time.

The lock associated with this condition is freed atomically, and the current thread is disabled for the purpose of thread scheduling, and the current thread will remain dormant until one of the following five situations occurs:

    • One of the other threads calls this Condition signal() method, and it happens that the current thread is selected as a wake-up thread;
    • One of the other threads calls this Condition signalAll() method;
    • One of the other threads interrupts the current thread, and supports the suspend of the threaded thread;
    • has exceeded the specified wait time;
    • " false Wakeup " occurs.

In all cases, the lock associated with this condition must be re-acquired before this method can return the current thread. When a thread returns, it is guaranteed to hold the lock.

If the current thread:

    • The interrupt state of the thread has been set when entering this method;
    • The thread is interrupted while the wait and interrupt threads are pending.
is thrown InterruptedException, and clears the interrupted state of the current thread. In the first case, you do not specify whether the break test occurs before the lock is released.

On return, the method returns an estimate of the number of nanoseconds remaining to wait for the supplied value and, nanosTimeout if timed out, returns a value less than or equal to 0. You can use this value to determine whether you want to wait again, and the time to wait again, if you wait for the return but still do not have a wait condition. Typical uses of this method take the following form:

Synchronized Boolean Amethod (long timeout, timeunit unit) {   Long nanostimeout = Unit.tonanos (timeout);   while (!conditionbeingwaitedfor) {     if (nanostimeout > 0)         nanostimeout = Thecondition.awaitnanos ( Nanostimeout);      else        return false;   }   // ...  

Design considerations: This method requires a nanosecond parameter to avoid truncation errors when the time remaining is reported. This loss of precision in the event of a re-wait makes it difficult for programmers to ensure that the total wait time is not less than the specified wait time.

Implementation Considerations

Assuming that this method is called, the current thread maintains a Condition lock associated with this. This depends on the implementation to determine if this is the case and how to respond to it. Usually throws an exception (for example IllegalMonitorStateException ) and the implementation must record it.

The implementation may prefer to respond to an interrupt when compared to the normal method returned in response to a signal, or to a specified wait time that indicates the use. In either case, the implementation must ensure that the signal is redirected to another waiting thread, if any.

Parameters:
nanosTimeout-The maximum amount of time to wait, in nanoseconds
Return:
nanosTimeoutValue minus the estimate of the time spent waiting for the return result of this method. A positive value can be used as a parameter for subsequent calls to this method to complete the wait time to finish. Values less than or equal to zero indicate no time remaining.
Thrown:
InterruptedException -If the current thread is interrupted (and the support is suspended)
4. Boolean await (long time,  Timeunit unit) throwsInterruptedexception causes the current thread to wait until it receives a signal, is interrupted, or arrives at a specified wait time. This method is equivalent in behavior to: Awaitnanos (Unit.tonanos (time)) > 0

Parameters:
time -Maximum wait time
unit - time The time unit of the parameter
Return:
Returns if the wait time timeout is detected before this method returns false , otherwise true
Thrown:
InterruptedException -If the current thread is interrupted (and the support is suspended)

5. Boolean Awaituntil (Date deadline) throws Interruptedexception causes the current thread to wait until it receives a signal, is interrupted, or arrives at a specified deadline.

The lock associated with this condition is freed atomically, and the current thread is disabled for the purpose of thread scheduling, and the current thread will remain dormant until one of the following five situations occurs:

    • One of the other threads calls this Condition signal() method, and it happens that the current thread is selected as a wake-up thread;
    • One of the other threads calls this Condition signalAll() method;
    • One of the other threads interrupts the current thread, and supports the suspend of the threaded thread;
    • The specified deadline has arrived;
    • " false Wakeup " occurs.

In all cases, the lock associated with this condition must be re-acquired before this method can return the current thread. When a thread returns, it is guaranteed to hold the lock.

If the current thread:

    • The interrupt state of the thread has been set when entering this method;
    • The thread is interrupted while the wait and interrupt threads are pending.
is thrown InterruptedException, and clears the interrupted state of the current thread. In the first case, you do not specify whether the break test occurs before the lock is released.

The return value indicates whether the deadline is reached, using the following method:

Synchronized Boolean Amethod (Date deadline) {   Boolean stillwaiting = true;   while (!conditionbeingwaitedfor) {     if (stillwaiting)         stillwaiting = Thecondition.awaituntil (deadline);      else        return false;   }   // ...  

Implementation Considerations

Assuming that this method is called, the current thread maintains a Condition lock associated with this. This depends on the implementation to determine if this is the case and how to respond to it. Typically, an exception is thrown (for example IllegalMonitorStateException ) and the implementation must record it.

The implementation may prefer to respond to an interrupt compared to a normal method returned in response to a signal, or to a specified deadline. In either case, the implementation must ensure that the signal is redirected to another waiting thread, if any.

Parameters:
deadline-Absolute time in the waiting state
Return:
Returns if the deadline has been reached on return false , otherwise true
Thrown:
InterruptedException -If the current thread is interrupted (and support threads are suspended)
6, void signal () wakes up a waiting thread.

If all the threads are waiting for this condition, select one of the wakes. awaitThe thread must regain the lock before returning from it.


7, void Signalall() wakes all waiting threads.

If all the threads are waiting for this condition, all threads are awakened. awaitEach thread must regain the lock before returning from it.






Condition in Java

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.