Java util concurrent condition

Interface Condition

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.

Источник

Java Concurrency — Condition Interface

A java.util.concurrent.locks.Condition interface provides a thread ability to suspend its execution, until the given condition is true. A Condition object is necessarily bound to a Lock and to be obtained using the newCondition() method.

Condition Methods

Following is the list of important methods available in the Condition class.

Causes the current thread to wait until it is signalled or interrupted.

public boolean await(long time, TimeUnit unit)

Causes the current thread to wait until it is signalled or interrupted, or the specified waiting time elapses.

public long awaitNanos(long nanosTimeout)

Causes the current thread to wait until it is signalled or interrupted, or the specified waiting time elapses.

public long awaitUninterruptibly()

Causes the current thread to wait until it is signalled.

public long awaitUntil()

Causes the current thread to wait until it is signalled or interrupted, or the specified deadline elapses.

Wakes up one waiting thread.

public void signalAll()

Wakes up all waiting threads.

Example

The following TestThread program demonstrates these methods of the Condition interface. Here we’ve used signal() to notify and await() to suspend the thread.

import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class TestThread < public static void main(String[] args) throws InterruptedException < ItemQueue itemQueue = new ItemQueue(10); //Create a producer and a consumer. Thread producer = new Producer(itemQueue); Thread consumer = new Consumer(itemQueue); //Start both threads. producer.start(); consumer.start(); //Wait for both threads to terminate. producer.join(); consumer.join(); >static class ItemQueue < private Object[] items = null; private int current = 0; private int placeIndex = 0; private int removeIndex = 0; private final Lock lock; private final Condition isEmpty; private final Condition isFull; public ItemQueue(int capacity) < this.items = new Object[capacity]; lock = new ReentrantLock(); isEmpty = lock.newCondition(); isFull = lock.newCondition(); >public void add(Object item) throws InterruptedException < lock.lock(); while(current >= items.length) isFull.await(); items[placeIndex] = item; placeIndex = (placeIndex + 1) % items.length; ++current; //Notify the consumer that there is data available. isEmpty.signal(); lock.unlock(); > public Object remove() throws InterruptedException < Object item = null; lock.lock(); while(current item = items[removeIndex]; removeIndex = (removeIndex + 1) % items.length; --current; //Notify the producer that there is space available. isFull.signal(); lock.unlock(); return item; > public boolean isEmpty() < return (items.length == 0); >> static class Producer extends Thread < private final ItemQueue queue; public Producer(ItemQueue queue) < this.queue = queue; >@Override public void run() < String[] numbers = ; try < for(String number: numbers) < System.out.println("[Producer]: " + number); >queue.add(null); > catch (InterruptedException ex) < ex.printStackTrace(); >> > static class Consumer extends Thread < private final ItemQueue queue; public Consumer(ItemQueue queue) < this.queue = queue; >@Override public void run() < try < do < Object number = queue.remove(); System.out.println("[Consumer]: " + number); if(number == null) < return; >> while(!queue.isEmpty()); > catch (InterruptedException ex) < ex.printStackTrace(); >> > >

This will produce the following result.

Output

[Producer]: 1 [Producer]: 2 [Producer]: 3 [Producer]: 4 [Producer]: 5 [Producer]: 6 [Producer]: 7 [Producer]: 8 [Producer]: 9 [Producer]: 10 [Producer]: 11 [Producer]: 12 [Consumer]: null

Источник

Кофе-брейк #223. Параллелизм в Java и интерфейс Condition. Перегрузка и переопределение метода в Java

Java-университет

Кофе-брейк #223. Параллелизм в Java и интерфейс Condition. Перегрузка и переопределение метода в Java - 1

Источник: DZone Благодаря этой статье вы узнаете, как заставить потоки ожидать определенных условий с помощью интерфейса Condition. Используя Condition , мы можем создавать механизмы, которые позволяют потокам ожидать выполнения определенных условий, прежде чем приступить к их выполнению.

 public interface Condition
  1. Получить lock .
  2. Проверить состояние.
  3. Обработать данные.
  4. Освободить lock .
  1. Получить lock .
  2. Проверить состояние.
  3. Ждем, пока не будет выполнено условие.
  4. Повторно получить lock .
  5. Обработать данные.
  6. Освободить lock .
  1. Получить lock .
  2. Опубликовать данные.
  3. Уведомить рабочие потоки.
  4. Освободить lock .
 package com.gkatzioura.concurrency.lock.condition; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class MessageQueue  < private Queuequeue = new LinkedList<>(); private Lock lock = new ReentrantLock(); private Condition hasMessages = lock.newCondition(); public void publish(T message) < lock.lock(); try < queue.offer(message); hasMessages.signal(); >finally < lock.unlock(); >> public T receive() throws InterruptedException < lock.lock(); try < while (queue.isEmpty()) < hasMessages.await(); >return queue.poll(); > finally < lock.unlock(); >> > 
 MessageQueue messageQueue = new MessageQueue<>(); @Test void testPublish() throws InterruptedException < Thread publisher = new Thread(() ->< for (int i = 0; i < 10; i++) < String message = "Sending message num: " + i; log.info("Sending [<>]", message); messageQueue.publish(message); try < Thread.sleep(1000); >catch (InterruptedException e) < throw new RuntimeException(e); >> >); Thread worker1 = new Thread(() -> < for (int i = 0; i < 5; i++) < try < String message = messageQueue.receive(); log.info("Received: [<>]", message); > catch (InterruptedException e) < throw new RuntimeException(e); >> >); Thread worker2 = new Thread(() -> < for (int i = 0; i < 5; i++) < try < String message = messageQueue.receive(); log.info("Received: [<>]", message); > catch (InterruptedException e) < throw new RuntimeException(e); >> >); publisher.start(); worker1.start(); worker2.start(); publisher.join(); worker1.join(); worker2.join(); > 

Перегрузка и переопределение метода в Java

Источник: Medium В этой публикации объясняется разница между переопределением метода и перегрузкой метода в Java. Перегрузка метода и переопределение метода являются двумя важными понятиями в языке Java. Каждый из них выполняет свою роль при использовании методов в объектно-ориентированном программировании.

Перегрузка метода

В Java перегрузка метода (overload) позволяет создавать несколько методов с одинаковыми именами в одном классе. Списки параметров для методов должны быть разными (то есть, они должны иметь разные типы или количество параметров). Когда вы вызываете перегруженный метод, компилятор Java выбирает версию для вызова на основе аргументов, которые вы предоставляете методу.

 public class CalculateOps < public void add(int x) < // реализация метода для int >public void add(float x) < // реализация метода для float >public void add(int x,float y) < // реализация метода для int и float >> CalulateOps calculateOps=new CalculateOps() calculateOps.add(5)// это вызовет метод первого целочисленного параметра calculateOps.add(5.5f)// это вызовет первый метод параметра с плавающей запятой 

В приведенном выше примере мы определили методы с одинаковыми именами ( add ), но с разными списками параметров (один принимает int , а другой — float ). Когда мы вызываем add , компилятор Java определяет, какую версию метода вызывать, основываясь на аргументе, который мы ему передаем. Вы не можете объявить несколько методов с одинаковым номером и одним и тем же типом параметра, лишь создавая разные типы возвращаемого значения. Это приведет к ошибке переопределения метода.

Переопределение метода

Переопределение метода (override) — это метод Java, который позволяет подклассу предоставлять собственную реализацию метода, предоставленного его суперклассом. Метод подкласса должен иметь ту же сигнатуру (имя и параметры), что и метод суперкласса. Когда вы вызываете переопределенный метод для экземпляра подкласса, выполняется версия метода подкласса, а не версия суперкласса.

 public class SuperClass < public void test() < // реализация метода в суперклассе >> public class SubClass extends SuperClass < @Override public void test() < // реализация метода в подклассе >> SubClass subClass= new SubClass(); subClass.test();// будет вызван метод подкласса SuperClass superclass= new Subclass(); superclass.test()// будет вызван метод суперкласса 

Можно ли переопределить статический метод в Java?

Нет, переопределение здесь невозможно. С одной стороны, на перегрузку статического метода не накладывается никаких ограничений, поскольку компилятор считает, что методы с разным списком аргументов — это разные методы. Но это не переопределение. Метод с модификатором static относится к классу, а не к его объектам (например, экземпляру класса). Для него работает статическое связывание, поэтому переопределение в дочернем классе не работает. Тем не менее, в дочернем классе можно объявить метод static с такой же сигнатурой, как в родительском. В этом случае произойдет не перегрузка и не переопределение, а затенение (shadowing). К такому методу нельзя применить аннотацию @Override и в нем нельзя использовать ключевое слово super .

Источник

Читайте также:  Как перемешать словарь питон
Оцените статью