tommi
tommi

Reputation: 13

java ArrayBlockingQueue put and take at the same time will cause deadlock?

the ArrayBlockingQueue's take and put functions acting like these:

`final Object[] items = new Object[100];
   int putptr, takeptr, count;

   public void put(Object 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 {
       lock.unlock();
     }
   }

   public Object take() throws InterruptedException {
     lock.lock();
     try {
       while (count == 0)
         notEmpty.await();
       Object x = items[takeptr];
       if (++takeptr == items.length) takeptr = 0;
       --count;
       notFull.signal();
       return x;
     } finally {
       lock.unlock();
     }
   }
 }
` 

My question is suppose now there is no element in queue and i call take(). then the calling thread will be waiting by notEmpty.await() and at same time, the thread holds monitor of lock. if i call put() from another thread which suppose to add a new element into queue, the put() function will wait at line lock.lock() until take() calls unlock(). am i correct? if i am correct, there will be deadlock.

Upvotes: 0

Views: 825

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279960

No, the javadoc of Condition#await() states

The lock associated with this Condition is atomically released and the current thread becomes disabled for thread scheduling purposes and lies dormant until one of four things happens: [...]

So the Lock object is released and can be acquired by another thread.

Upvotes: 2

Related Questions