Totti
Totti

Reputation: 5

Is it necessary using while statement instead of if statement when using Thread wait() method in java

For example if I have this code :

public synchronized T get() throws Exception {
        while (!condition()) {
            try {
                wait();
            } catch (Exception e) {
                throw new Exception(e);
            }
            if (!condition()) {
                throw new Exception();
            }
        }

        ...
    }

Can I switch the while by if?

Upvotes: 0

Views: 45

Answers (1)

Yes, it is necessary.

For one thing: perhaps the following happens:

  1. Thread 1 starts waiting.
  2. Thread 2 starts waiting.
  3. Thread 3 makes the condition true and calls notifyAll.
  4. Thread 1 wakes up.
  5. Thread 1 makes the condition false again.
  6. Thread 2 wakes up.

Now thread 2 shouldn't just assume the condition is true, because it's not!

For another thing, spurious wakeups are possible. This means wait might return for no reason at all (or no reason relevant to your program) - for instance, it might return if a debugger attaches to your program.

Upvotes: 1

Related Questions