Java lock condition example
Condition factors out the Object monitor methods ( wait , notify and notifyAll ) into distinct objects to give the effect of having multiple wait-sets per object, by combining them with the use of arbitrary Lock implementations. Where a Lock replaces the use of synchronized methods and statements, a Condition replaces the use of the Object monitor methods. Conditions (also known as condition queues or condition variables) provide a means for one thread to suspend execution (to «wait») until notified by another thread that some state condition may now be true. Because access to this shared state information occurs in different threads, it must be protected, so a lock of some form is associated with the condition. The key property that waiting for a condition provides is that it atomically releases the associated lock and suspends the current thread, just like Object.wait . A Condition instance is intrinsically bound to a lock. To obtain a Condition instance for a particular Lock instance use its newCondition() method. As an example, suppose we have a bounded buffer which supports put and take methods. If a take is attempted on an empty buffer, then the thread will block until an item becomes available; if a put is attempted on a full buffer, then the thread will block until a space becomes available. We would like to keep waiting put threads and take threads in separate wait-sets so that we can use the optimization of only notifying a single thread at a time when items or spaces become available in the buffer. This can be achieved using two Condition instances.
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(E 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 > public E take() throws InterruptedException < lock.lock(); try while (count == 0) notEmpty.await(); E x = (E) items[takeptr]; if (++takeptr == items.length) takeptr = 0; --count; notFull.signal(); return x; > finally > >
(The ArrayBlockingQueue class provides this functionality, so there is no reason to implement this sample usage class.) A Condition implementation can provide behavior and semantics that is different from that of the Object monitor methods, such as guaranteed ordering for notifications, or not requiring a lock to be held when performing notifications. If an implementation provides such specialized semantics then the implementation must document those semantics. Note that Condition instances are just normal objects and can themselves be used as the target in a synchronized statement, and can have their own monitor wait and notify methods invoked. Acquiring the monitor lock of a Condition instance, or using its monitor methods, has no specified relationship with acquiring the Lock associated with that Condition or the use of its waiting and signalling methods. It is recommended that to avoid confusion you never use Condition instances in this way, except perhaps within their own implementation. Except where noted, passing a null value for any parameter will result in a NullPointerException being thrown.
Implementation Considerations
When waiting upon a Condition , a «spurious wakeup» is permitted to occur, in general, as a concession to the underlying platform semantics. This has little practical impact on most application programs as a Condition should always be waited upon in a loop, testing the state predicate that is being waited for. An implementation is free to remove the possibility of spurious wakeups but it is recommended that applications programmers always assume that they can occur and so always wait in a loop. The three forms of condition waiting (interruptible, non-interruptible, and timed) may differ in their ease of implementation on some platforms and in their performance characteristics. In particular, it may be difficult to provide these features and maintain specific semantics such as ordering guarantees. Further, the ability to interrupt the actual suspension of the thread may not always be feasible to implement on all platforms. Consequently, an implementation is not required to define exactly the same guarantees or semantics for all three forms of waiting, nor is it required to support interruption of the actual suspension of the thread. An implementation is required to clearly document the semantics and guarantees provided by each of the waiting methods, and when an implementation does support interruption of thread suspension then it must obey the interruption semantics as defined in this interface. As interruption generally implies cancellation, and checks for interruption are often infrequent, an implementation can favor responding to an interrupt over normal method return. This is true even if it can be shown that the interrupt occurred after another action that may have unblocked the thread. An implementation should document this behavior.
Method Summary
Causes the current thread to wait until it is signalled or interrupted, or the specified waiting time elapses.
Causes the current thread to wait until it is signalled or interrupted, or the specified waiting time elapses.
Causes the current thread to wait until it is signalled or interrupted, or the specified deadline elapses.
Java lock condition example
Применение условий в блокировках позволяет добиться контроля над управлением доступом к потокам. Условие блокировки представлет собой объект интерфейса Condition из пакета java.util.concurrent.locks .
Применение объектов Condition во многом аналогично использованию методов wait/notify/notifyAll класса Object, которые были рассмотрены в одной из прошлых тем. В частности, мы можем использовать следующие методы интерфейса Condition:
- await : поток ожидает, пока не будет выполнено некоторое условие и пока другой поток не вызовет методы signal/signalAll . Во многом аналогичен методу wait класса Object
- signal : сигнализирует, что поток, у которого ранее был вызван метод await() , может продолжить работу. Применение аналогично использованию методу notify класса Object
- signalAll : сигнализирует всем потокам, у которых ранее был вызван метод await() , что они могут продолжить работу. Аналогичен методу notifyAll() класса Object
Эти методы вызываются из блока кода, который попадает под действие блокировки ReentrantLock. Сначала, используя эту блокировку, нам надо получить объект Condition:
ReentrantLock locker = new ReentrantLock(); Condition condition = locker.newCondition();
Как правило, сначала проверяется условие доступа. Если соблюдается условие, то поток ожидает, пока условие не изменится:
while (условие) condition.await();
После выполнения всех действий другим потокам подается сигнал об изменении условия:
Важно в конце вызвать метод signal/signalAll, чтобы избежать возможности взаимоблокировки потоков.
Для примера возьмем задачу из темы про методы wait/notify и изменим ее, применяя объект Condition.
Итак, у нас есть склад, где могут одновременно быть размещено не более 3 товаров. И производитель должен произвести 5 товаров, а покупатель должен эти товары купить. В то же время покупатель не может купить товар, если на складе нет никаких товаров:
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.Condition; public class Program < public static void main(String[] args) < Store store=new Store(); Producer producer = new Producer(store); Consumer consumer = new Consumer(store); new Thread(producer).start(); new Thread(consumer).start(); >> // Класс Магазин, хранящий произведенные товары class Store < private int product=0; ReentrantLock locker; Condition condition; Store()< locker = new ReentrantLock(); // создаем блокировку condition = locker.newCondition(); // получаем условие, связанное с блокировкой >public void get() < locker.lock(); try< // пока нет доступных товаров на складе, ожидаем while (product<1) condition.await(); product--; System.out.println("Покупатель купил 1 товар"); System.out.println("Товаров на складе: " + product); // сигнализируем condition.signalAll(); >catch (InterruptedException e) < System.out.println(e.getMessage()); >finally < locker.unlock(); >> public void put() < locker.lock(); try< // пока на складе 3 товара, ждем освобождения места while (product>=3) condition.await(); product++; System.out.println("Производитель добавил 1 товар"); System.out.println("Товаров на складе: " + product); // сигнализируем condition.signalAll(); > catch (InterruptedException e) < System.out.println(e.getMessage()); >finally < locker.unlock(); >> > // класс Производитель class Producer implements Runnable < Store store; Producer(Store store)< this.store=store; >public void run() < for (int i = 1; i < 6; i++) < store.put(); >> > // Класс Потребитель class Consumer implements Runnable < Store store; Consumer(Store store)< this.store=store; >public void run() < for (int i = 1; i < 6; i++) < store.get(); >> >
В итоге мы получим вывод наподобие следующего:
Производитель добавил 1 товар Товаров на складе: 1 Производитель добавил 1 товар Товаров на складе: 2 Производитель добавил 1 товар Товаров на складе: 3 Покупатель купил 1 товар Товаров на складе: 2 Покупатель купил 1 товар Товаров на складе: 1 Покупатель купил 1 товар Товаров на складе: 0 Производитель добавил 1 товар Товаров на складе: 1 Производитель добавил 1 товар Товаров на складе: 2 Покупатель купил 1 товар Товаров на складе: 1 Покупатель купил 1 товар Товаров на складе: 0