-1

Say i have a count down latch like with count=1

Suppose i have two threads(T1, T2) waiting on latch. Say T1 came first and called latch.await() and later came T2

When latch is count down is there is guarantee that T1 will be executed first and later T2

xingbin
  • 27,410
  • 9
  • 53
  • 103
samuel koduri
  • 389
  • 2
  • 4
  • 9
  • No, there is no such guarantee, at least not by documentation of `CountDownLatch`. It just guarantees that no thread will continue after an `await` until the count is zero, – user85421 Mar 13 '18 at 12:50

2 Answers2

1

No, there is no such guarantee, CountDownLatch dose not have a fair policy.

However, ReentrantLock and Condition have fair policy:

Waiting threads are signalled in FIFO order.

The ordering of lock reacquisition for threads returning from waiting methods is the same as for threads initially acquiring the lock, which is in the default case not specified, but for fair locks favors those threads that have been waiting the longest.

So if you want the waiting threads wake up in fifo order, you can combine CountDownLatch and Condition:

Create a ReentrantLock:

 ReentrantLock lock = new ReentrantLock(true);
 Condition condition = lock.newCondition();

Let T1 and T2 wait on this condition:

lock.lock();
try {
    while (...) {
        condition.await();     
    }
} finally {
    lock.unlock();
}
doSomething();

Create a new thread T3 wait on CountDownLatch and signal T1 & T2:

countDownLatch.await();
lock.lock();
try {
    condition.signalAll();
} finally {
    lock.unlock();
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
xingbin
  • 27,410
  • 9
  • 53
  • 103
0

This might vary according to how the underlying operating system manages threads, but in my experience (on Windows) the order in which a thread acquires a lock (semaphore or mutex) is never guaranteed. If one thread has a higher priority then logically that ought to make a difference, but that is outside of my experience so I can't say whether it does in practice.

Brian Cryer
  • 2,126
  • 18
  • 18