MichBoy
MichBoy

Reputation: 299

Using wait() without notify() when in synchronized code piece (java)

I wanted to know if it's possible to use wait() on a synchronized piece of code without using notify(), something like this:

wait_on(B):
    synchronized(B.monitor) {
    B.count--
        while (B.count > 0) { /* wait */ }
    }

Thanks in advance

Upvotes: 2

Views: 2995

Answers (4)

Nathan Hughes
Nathan Hughes

Reputation: 96385

You need notify or notifyAll to awaken the thread from its wait state. In your sample the code would enter the wait and stay there (unless interrupted).

Know the difference between wait, yield, and sleep. Wait needs to be called in a synchronized block, once the wait is entered the lock is released, and the thread stays in that state until notify is called. Yield returns the thread to the ready pool and lets the scheduler decide when to run it again. Sleep means the thread goes dormant for a fixed period of time (and from there it goes to the ready pool).

Make sure you call wait on the same object that you’re synchronizing on (here it’s B.monitor).

Upvotes: 5

Pierre-Luc Bertrand
Pierre-Luc Bertrand

Reputation: 740

If it is a barrier that you want, you will need to notifyAll your other threads:

wait_on(B) {
    synchronized(B.monitor) {
        B.count--
        while (B.count > 0) {
            B.monitor.wait()
        }
        B.monitor.notifyAll();
    }
}

Regards,

Pierre-Luc

Upvotes: 0

Eran Zimmerman Gonen
Eran Zimmerman Gonen

Reputation: 4507

If you change the /* wait */ into a call to wait(), and no one will call notify() or notifyAll(), then this thread will never wake up...

Upvotes: 0

Kalpak Gadre
Kalpak Gadre

Reputation: 6475

No! Only option is to wait with a timeout, which surely will not help you.

Upvotes: 0

Related Questions