2

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

3
  • 9
    Sure, if you want it to wait for all eternity for a notify. Commented Apr 19, 2012 at 18:39
  • How to you reckon to come out of the wait() state without a notify()? What you are doing is some what equivalent to killing the thread without actually doing it. Commented Apr 19, 2012 at 18:41
  • will it work without the synchronized? Commented Apr 19, 2012 at 18:52

4 Answers 4

5

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).

Sign up to request clarification or add additional context in comments.

6 Comments

But that happens until all threads will enter this method, and the last one will cause the count to be 0, then it'll get out, which will make an automatic notify(), or am I wrong?
@MichBoy: there's no 'automatic' notify. once the counter goes to 0 then no more threads will enter the body of the while loop, that is all that will happen.
and if I get the synchronized off?
@MichBoy: are you trying to implement a counting semaphore? because java.util.concurrent has those already: docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/…
I'm trying to do something similar but different, will it work without the synchronized?
|
0

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

Comments

0

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...

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.