4

Here is the example.

class Factory {
    Queue<Object> queue = new LinkedBlockingQueue<Object>();

    public Object consume() {
        queue.take();
    }

    public void produce() {
        for (int i = 0; i < 2; i++) {
            queue.put(new Object());
        }
    }
}

For example I have two threads which both called consume(). They are waiting for a producer to put something in the queue. My question is whether after a put() action a take() action happens, or is it possible for two put() actions to happen one after the other and only after that the waiting threads will return ?

Thank you.

Shahin
  • 93
  • 1
  • 8
  • 1
    `BlockingQueue` is an `interface`. In any case; don't assume any order when it comes to threads. Most likely the `take()` will happen after the `put()` - but it might happen that the tread woken by the `put()` might be beaten to the punch by the other other `put()`. – Boris the Spider Feb 04 '14 at 00:59

1 Answers1

1

As soon as put finishes, lock is released now lets assume put and take both are waiting on that lock again and its unfair lock then any of the methods Put/Take can get hold of lock and start. There is no ordered and alternate exchange of monitor(lock) unless specified.

See the code by java.

ArrayBlockingQueue

ReentrantLock

AbstractQueuedSynchronizer

Rohit Sachan
  • 1,178
  • 1
  • 8
  • 16