0

Right now ,i am preparing for java ocajp 8 certification and just looking through some dumps and it says that following code throws IllegalStateException;

and code is below` 

void waitForSignal() throws Exception{
    Object obj = new Object(); 
    synchronized (Thread.currentThread()) {
        obj.wait(); 
        obj.notify(); 
    } 
}` 

Preceding code is all it provided and nothing else ,why does a exception arise here and fact is i know little about multithreading. and according to java documentation

IllegalStateException : Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation.

So i suppose wait() or notify() is invoked at inappropriate time... if i am right why is it illegal time and if i am wrong ,then explain why exception arises..

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
manifold
  • 437
  • 6
  • 23
  • 2
    I'm afraid multi-threading in Java isn't something that can be learned via trial and error. (Or at least it takes a LOT of trial.) In this case the problem is that you don't have the monitor of `obj`. – biziclop Jun 24 '16 at 10:48
  • 2
    As an aside, synchronizing on a Thread object is a Very Bad Idea™.. – biziclop Jun 24 '16 at 10:50
  • 1
    @biziclop So, we can only call wait or notify on some object when we have lock on that object but here we have lock on some thread object, so that is reason the for illegalstateexception ? correct me if am wrong – manifold Jun 24 '16 at 10:50
  • Exactly. See Boola's answer. – biziclop Jun 24 '16 at 10:51
  • That snippet creates a new `Object obj`, and then it immediately calls `obj.wait()` without making the object available to any other thread. How does that make any sense? – Solomon Slow Jun 24 '16 at 15:07

1 Answers1

2

You can't wait() on an object unless the current thread owns that object's monitor. To do that, you must synchronize on it:

synchronized (obj) {

According to javadoc :

public class IllegalMonitorStateException extends RuntimeException Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.

Boola
  • 358
  • 3
  • 14