Pankaj Kumar
Pankaj Kumar

Reputation: 255

What is missed signal in java? how calling notify() be missed by the waiting thread?

I was going through one concurrency tutorial by Jakob Jenkov. In this he mentioned sometimes notify() signal can be missed by waiting thread. How is this possible?

public class MissedSignal {

    //boolean wasSignalled = false;
    public void doWait() {
        synchronized (this) {
            //if(!wasSignalled){

            try {
                this.wait();
            } catch (InterruptedException e) {
            }
            //}
        }
    }

    public void doNotify() {
        synchronized (this) {
            //wasSignalled = true;

            this.notify();
        }

    }
}

I am not able to understand the use of commented part of this code. As i think the notify()signal would never be missed by waiting thread? Could someone please explain... I am new to java and i didn't find answers of this on google.... Thanks in Advance

Upvotes: 4

Views: 1542

Answers (2)

TwoThe
TwoThe

Reputation: 14289

Hint:

public synchronized void foo() { ... }

is the exact same as

public void foo() { synchronized(this) { ... } }

It is better to use the first version for ease of reading and possible compiler optimizations.

Upvotes: -2

Alexei Kaigorodov
Alexei Kaigorodov

Reputation: 13535

Signal can be missed if doNotify called before doWait. So doNotify should mark somehow that it was called. The usual way for this is using a variable. Uncomment all usages of wasSignalled and the signal will not be missed.

Upvotes: 8

Related Questions