class Test {
public static void main(String[] args) {
System.out.println("1.. ");
synchronized (args) {
System.out.println("2..");
try {
Thread.currentThread().wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("3..");
}
}
}
I am getting IllegalMonitorStateException
monitor exception in this code. As per my understanding, because of synchronized block around args
which is string array object, current thread must have acquired the lock and with the wait method, I am release the lock.
Can someone explain me the reason behind this exception?
You're calling
wait()
onThread.currentThread()
. Before callingwait()
on any object, you must own the monitor of this object, by the way of a synchronized block synchronizing on this object. So what is missing isThat said, calling
wait()
on a Thread object is not something you should do, and probably shows that you have not understood whatwait()
does, especially given that you don't have any other thread callingnotify()
ornotifyAll()
. Synchronizing on the arguments passed to the main method is also a very strange choice.wait()
is a very low-level method that should rarely be used, even if you fully understand what it does. For a better answer, you should explain what you actually want this code to do.Hi ankit i assume you are trying to learn some basic concepts of multithreading. try to get hold of some good online tutorials :http://www.javaworld.com/jw-04-1996/jw-04-threads.html
or try some basic good book. http://www.amazon.com/SCJP-Certified-Programmer-Java-310-065/dp/0071591060/
The program you wrote actually doesn't need synchronization as there is only one thread (main). I know you are just trying your hands, therefore giving some insights. Even if you correctly called wait method on args(args.wait()) or synchronized on Thread.currentThread your thread may goes into indefinite wait (making your program unresponsive) because there is no other thread to notify your main thread.
From
IllegalMonitorStateException
documentationFrom
Object#notify()
documentationSo since thread is executing block synchronized on
args
objectyou should call
args.wait()
insteadThread.currentThread().wait();
.