Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do threads spontaneously awake from wait()?

I was wondering why threads spontaneously awake from wait() in java.
Is it a design decision? Is it a compromise?

EDIT: (from Java Concurrency in Practice, p. 300)

wait is even allowed to return "spuriously" - not in response to any thread calling notify.

Further the authors state:

this is like a toaster with a loose connection that makes the bell go off when the toast is ready but also sometimes when it is not ready.

This is why you always have to code like

synchronized(this){
    while(!condition)
        wait();
    }
}

and never

synchronized(this){
    if(!condition){
        wait();
    }
}

Even if the condition transitions only from false to true.

like image 232
Enno Shioji Avatar asked Mar 29 '10 20:03

Enno Shioji


People also ask

What causes spurious wakeup?

A spurious wakeup happens when a thread wakes up from waiting on a condition variable that's been signaled, only to discover that the condition it was waiting for isn't satisfied. It's called spurious because the thread has seemingly been awakened for no reason.

What happens when a thread executes wait () method on an object without owning the object's lock?

For a thread to call wait() or notify(), the thread has to be the owner of the lock for that object. When the thread waits, it temporarily releases the lock for other threads to use, but it will need it again to continue execution.

How wait and notify works internally in Java?

The wait() Method Simply put, calling wait() forces the current thread to wait until some other thread invokes notify() or notifyAll() on the same object. For this, the current thread must own the object's monitor.

How to make main thread wait in Java?

sleep in Java. Thread. sleep() method can be used to pause the execution of current thread for specified time in milliseconds.


1 Answers

These spontaneous wakeups are also called "spurious wakeups". In the Java specification, the spurious wakeups are permitted (though not encouraged) for jvm implementations.

The reason they are permitted is because many implementations may be based on pthreads (POSIX threads), that have this behaviour. Why?

Wikipedia:

According to David R. Butenhof's Programming with POSIX Threads ISBN 0-201-63392-2: "This means that when you wait on a condition variable, the wait may (occasionally) return when no thread specifically broadcast or signalled that condition variable. Spurious wakeups may sound strange, but on some multiprocessor systems, making condition wakeup completely predictable might substantially slow all condition variable operations. The race conditions that cause spurious wakeups should be considered rare."

like image 182
bitc Avatar answered Sep 27 '22 22:09

bitc