Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use "while" in the await method of AQS(AbstractQueuedSynchronizer)

In the await method of AQS (AbstractQueuedSynchronizer): I want to know the meaning of while in while (!isOnSyncQueue(node)) {

I think that if this node is woken up normally (without being interrupted), It will definitely be moved to the sync queue after the signal method is executed by another thread, and then woken up by executing the unlock method in another thread.

So there could be a situation where a node is waking up normally, but not in the sync queue? If that's not possible, I think if should be used here instead of while

public final void await() throws InterruptedException {
    if (Thread.interrupted())
        throw new InterruptedException();
    Node node = addConditionWaiter();
    int savedState = fullyRelease(node);
    int interruptMode = 0;
    while (!isOnSyncQueue(node)) {
        LockSupport.park(this);
        if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
            break;
    }
    if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
        interruptMode = REINTERRUPT;
    if (node.nextWaiter != null) // clean up if cancelled
        unlinkCancelledWaiters();
    if (interruptMode != 0)
        reportInterruptAfterWait(interruptMode);
}

like image 353
Robert Hou Avatar asked Dec 28 '25 04:12

Robert Hou


2 Answers

Wakeups come in two flavours. The usual kind and the spurious kind. This code:

while (!isOnSyncQueue(node)) {
    ...
}

Keeps looping until isOnSyncQueue(node) returns false and is a while instead of an if, because the wake up might be spurious and not because the condition being waited for has occurred.

like image 148
Bohemian Avatar answered Dec 30 '25 17:12

Bohemian


while (!isOnSyncQueue(node)) {
    LockSupport.park(this);
    if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
        break;
}

What this does is execute the commands inside the pair of curly braces {}, until isOnSyncQueue(node) returns false. If it was an if instead of a while those statements would be executed only once.

like image 35
JustAnotherDeveloper Avatar answered Dec 30 '25 17:12

JustAnotherDeveloper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!