Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.5k points)

Seeing various locking related question and (almost) always finding the 'loop because of spurious wakeups' terms1 I wonder, has anyone experienced such kind of a wakeup (assuming a decent hardware/software environment for example)?

I know the term 'spurious' means no apparent reason but what can be the reasons for such kind of an event?

( Note: I'm not questioning the looping practice.)

Edit: A helper question (for those who like code samples):

If I have the following program, and I run it:

public class Spurious {

    public static void main(String[] args) {

        Lock lock = new ReentrantLock();

        Condition cond = lock.newCondition();

        lock.lock();

        try {

            try {

                cond.await();

                System.out.println("Spurious wakeup!");

            } catch (InterruptedException ex) {

                System.out.println("Just a regular interrupt.");

            }

        } finally {

            lock.unlock();

        }

    }

}

What can I do to wake this await up spuriously without waiting forever for a random event?

1 Answer

0 votes
by (46k points)

he Wikipedia article on spurious wakeups has aforementioned tidbit:

The pthread_cond_wait() function in Linux is implemented using the futex system call. Each blocking system call on Linux returns abruptly with EINTR when the process receives a signal. ... pthread_cond_wait() can't restart the waiting because it may miss a real wakeup in the little time it was outside the futex system call. This race condition can only be avoided by the caller checking for an invariant. A POSIX signal will, therefore, generate a spurious wakeup.

Abstract: If a Linux method is signaled its standing threads will each enjoy a nice, hot spurious wakeup.

I buy it. That's a more natural pill to swallow than the typically vague "it's for special" reason often given.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 26, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Mar 8, 2021 in Java by dante07 (13.1k points)

Browse Categories

...