Yokupoku Maioku
Yokupoku Maioku

Reputation: 503

clarification on take method of LinkedBlockingQueue

i have a LinkedBlockingQueue, and some threads that operate on it.

 public void run(){
     ...
      foo(linkedBlockingQueue.take());
     ...
   }

    public void foo(Object o){
       synchronized(o){
              //operate on the object
              ....
              //after operate re-insert the object inside the queue
       }
    }

if i have this situation:

a blocking queue with 5 elements and the "luckiest" thread have gained the control of the first element so:

thanks in advance.

Upvotes: 1

Views: 93

Answers (1)

dcernahoschi
dcernahoschi

Reputation: 15230

a blocking queue with 5 elements and the "luckiest" thread have gained the control of the first element so:

other threads that concurrently wanted the first element will put in wait?.

No, the other threads will get second, third and so on element until the queue is empty. Only in this case they will block.

it is useless to use a synchronized block if the first sentence is right?

The answer to this has nothing to do with answer to first question. If you process the taken object in a single thread or is immutable, then yes, synchronization is not needed, but you might need it otherwise.

other threads can access other positions on the interval when pickup the first element and insertion of this one without mutex exclusion?

You are asking if other threads might get more elements from the queue until the first one is re-added? Yes, the queue is not locked, it can be accessed from other threads.

Upvotes: 3

Related Questions