Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BlockingQueues and thread access order

I have a situation where multiple threads will be polling a single BlockingQueue by calling take(). What I want to know is the following:

If multiple threads are waiting for the queue to receive an item, will they be given priority for taking items off the queue in the order that they made their calls to take() or will the order in which the threads take things off the queue be arbitrary?

Thanks!

Note: I have written my own implementations for this kind of thing in the past, but I'm wondering if the BlockingQueue implementations in Java would do this for me.

like image 774
Surveon Avatar asked Aug 27 '13 14:08

Surveon


1 Answers

It depends on the implementation.

If you use a LinkedBlockingQueue, the take() method checks with a ReentrantLock

public E take() throws InterruptedException {
    E x;
    int c = -1;
    final AtomicInteger count = this.count;
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lockInterruptibly();
    ...
}

// declared as
private final ReentrantLock takeLock = new ReentrantLock(); // no fairness argument, defaults to false

The javadoc says

The constructor for this class accepts an optional fairness parameter. When set true, under contention, locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order. Programs using fair locks accessed by many threads may display lower overall throughput (i.e., are slower; often much slower) than those using the default setting, but have smaller variances in times to obtain locks and guarantee lack of starvation. Note however, that fairness of locks does not guarantee fairness of thread scheduling. Thus, one of many threads using a fair lock may obtain it multiple times in succession while other active threads are not progressing and not currently holding the lock. Also note that the untimed tryLock method does not honor the fairness setting. It will succeed if the lock is available even if other threads are waiting.

like image 187
Sotirios Delimanolis Avatar answered Sep 24 '22 11:09

Sotirios Delimanolis