Question

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.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top