简体   繁体   中英

Spurious wakeup with Semaphore

I have a doubt: let's assume I have an object of class Semaphore called sem and that a thread tries to acquire a permission doing sem.acquire() and that there are not, so the thread is suspended. Now if the thread is awakened by a spurious wakeup, what happend? Should I insert the sem.acquire() in a sort of loop?

Only the very basic Object.wait() method is subjected to spurious wakeups (actually only the Unsafe.park() method, but there is no way to access that without hacks), all more sophisticated tools deal with that internally.

If you have a look at the actual code of Semaphore.acquireUninterruptibly() you'll find the following construct (hidden in AbstractQueuedSynchronizer.doAcquireShared() ):

for (;;) {
    // ... try aquire, else:
    if (shouldParkAfterFailedAcquire(p, node) &&
        parkAndCheckInterrupt())
        interrupted = true;
}

The for(;;) loop is basically a while(true) loop, so even though parkAndCheckInterrupt() can spuriously wake up, the loop will ensure that this will just cause another failed tryAquire run, then it will be put back to sleep.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM