Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Signalling threads in a lock's condition

I have taken the following points from this API and I would like to know the difference between the 2 following points:

  1. Waiting threads are signalled in FIFO order.

  2. 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.

It is related to Condition class which is usually returned by the ReentrantLock method .newCondition(), and the bit I quoted it's explaining the difference between the methods of Condition and the regular monitor methods of the Object class.

"Waiting threads are signalled in FIFO order". I think that as long as a lock is created either fair or not, the fact that the waiting threads are signalled in a FIFO order is totally irrelevant isn'it? because anyhow it's whether they have been constructed, fair or not, which decides how they are queued.

Just asking for a confirmation.

Thanks in advance.

like image 613
Rollerball Avatar asked Jul 23 '13 14:07

Rollerball


1 Answers

Please see below answers to your questions:

1.Waiting threads are signalled in FIFO order.

When we invoke await() method of Condition, thread goes into waiting state, the above statement refers to how these threads in waiting state are signalled. So if threads T1 went to waiting state before T2, T1 will be signalled before T2.

2.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.

In continuation to above statement, when waiting thread is signalled, it tend to reaquire lock. Though above statement says T1 will be signalled before T2, but when it comes to reaquiring lock, the order of reacquisition uses concepts defined by Lock. So, it depends on how Lock object was created. While creating Lock you might have specified a fairness parameter:

ReentrantLock(boolean fair)

If yes then that parameter is used, if not then default behaviour of locks happens, you can read more on ReentrantLock Locks at this link

There could be more explanations to these statements, just tried to best detail my understanding here. Hoping was able to clarify.

Cheers !!

like image 86
Sachin Thapa Avatar answered Nov 05 '22 00:11

Sachin Thapa