Is CyclicBarrier.getNumberWaiting() accurate?

115 Views Asked by At

I analysis the code in jdk1.8, but may have same issue in other jdk version

  1. Let's assume the parties = 3 in the following code

    CyclicBarrier cb = new CyclicBarrier(3);

enter image description here

parties = 3 and count > = 0, so the return value of getNumberWaiting() <= 3 but in some certain cases, more than 3 threads will be waiting 2.let's see the key code in CyclicBarrier

enter image description here

a) thread A in position 2 will return 0, now there are 2 threads await in position 3

b) after thread A execute lock.unlock(), thread B in position 1 get the lock(but the lock is unfair), so now index = 2, count =2, it will await in position 3, so now there are 3 threads await in position 3

c) let's assume, the lock will always be got by the thread from position 1, so the number of waiting thread will be more and more

so the getNumberWaiting() > 3 is the result

getNumberWaiting() = (cyclic numbers) * parties - count

1

There are 1 best solutions below

5
drekbour On

I think you need to look at the "generation" concept a little more. In your scenario, Thread A will have called nextGeneration() which resets all counts (getNumberWaiting() = 0) and signals all current waiters. Those waiters (on the now-previous generation) will shortly start completing.

So yes, there may be >3 threads against the trip Condition but 2 x old waiters have been signalled to leave and any new ones are awaiting a new signal. The getNumberWaiting is not computed using Lock.getHoldCount() so this is OK.