0

Two questions regarding synchronization

  1. What happen if using wait and notify methods in non synchronized blocks ? Is it useful ?
  2. Should synchronized object be the same as the object of the wait method ? Can I do like this :

    synchronized (o) { try { this.wait(); } catch (InterruptedException e) { } } 
2
  • You got your test program. Test it yourself. You will get the answer pretty quickly. Commented Jun 25, 2015 at 19:34
  • 2
    Did you try running the code or reading the javadoc? What don't you understand from these obvious ways to find out? Commented Jun 25, 2015 at 19:34

2 Answers 2

1
  1. An IllegalThreadStateException is thrown if the current thread fails to synchronize on an object before calling its wait() or notify() methods. So, no, it isn't useful.

  2. Yes, to reiterate the above, the thread must synchronize on the same instance upon which it invokes wait() or notify(). So the example will only work if o == this.

I don't find good reasons to use wait() and notify() since java.util.concurrent was introduced, and synchronized is less useful now too. I recommend the higher-level tools in that package to both beginners (as easier to use) and advanced (more powerful and correct) programmers.

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

2 Comments

rgarding point 1 : who own the monitor of an object that is not on synchronize ? nobody ?
@yryrp Right, no thread owns the monitor until one enters the critical section.
1

1. You can't call wait() or notify()/notifyAll() outside of synchronized blocks that synchronize on the the object the method calls belong to. If you try, you'll get an IllegalMonitorStateException.

2. You are required to synchronize on the same object that your wait()/notify()/notifyAll() calls belong to. For instance, your code will throw an IMSE as written. You'll want to call synchronized(this){ ... instead.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.