zer0uno
zer0uno

Reputation: 8030

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?

Upvotes: 1

Views: 1348

Answers (1)

TwoThe
TwoThe

Reputation: 14289

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.

Upvotes: 1

Related Questions