Saturday 20 March 2010

Java.util.Concurrent, Part 2 - Conditions

In the Java 5 and newer API, Conditions are Object designed to replace the simple wait and notify tasks in the earlier API. You get a Condition object, by calling the NewCondition method on any lock, you can make as many Conditions as you like on one lock. You can make a thread wait on the Condition one of 5 ways.






void await()Until a Signal or Interrupted
booleanawait(long, TimeUnit unit)For a set time, or a Signal or Interrupted, returns true if woken by Signal or Interrupt
longawaitNanos()Wait a time in Nanoseconds, return how much waiting time was left, if signalled
voidawaitUniterruptable()Only a Signal will awake this method
booleanawaitUntil(Date deadline)Waits until deadline or signalled, return true if signalled


All these methods, release the lock the condition was make from, where waiting. One
of to method might be used to singal the waiting condition.


voidsignal()Signal to wake one waiting condition
voidsignalAll()Signal to wake all waiting conditions


In a queue example, we would want to wake up only one waiting thread. But if a major tasked finished, we might wan't to wake up a the waiting threads.

No comments:

Post a Comment