简体   繁体   中英

Unbounded Blocking Queue Java

Requirement: Implement unbounded blocking queue ie thread calling get should block if no element present in queue.

public class BlockingQueue<T> {

  private Queue<T> queue = new LinkedList<>();
  private Object monitor = new Object();

  /**
   * add element to queue
   */
  public void add(T element) {
    synchronized (monitor) {
      queue.add(element);
      monitor.notify();
    }
  }

  /**
   * Returns element if present in queue
   * otherwise calling thread blocks until an element is added to queue
   *
   * @return element from queue
   */
  public T get() throws InterruptedException {
    synchronized (monitor) {
      while (queue.isEmpty()) {
        monitor.wait();
      }
      return queue.poll();
    }
  }
}

Questions
1. is implementation correct ?
2. invoking wait(); moves thread from RUNNABLE to WAIT state
invoking notify(); moves thread from WAIT to BLOCKED state
which action moves thread from BLOCKED to RUNNABLE state ?

Is the implemntation correct?

Yes

Just one remark : you may want to make the monitor field final .

Which action moves thread from BLOCKED to RUNNABLE state ?

The action of a thread releasing the lock the BLOCKED thread is waiting for.

Of course it could be that another thread acquires the lock on the monitor, and then this thread will remain BLOCKED until it gets a chance to acquire the lock on the monitor itself.

For clarity, a call of wait() on a monitor causes the calling thread go into WAIT state, but it also causes the thread to release all its locks on monitors. When such a thread is notified, it becomes BLOCKED because it needs to reacquire all the locks on all the monitors it had before, before it can continue. That is why it goes from WAIT to BLOCKED first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM