Not clear...can you please explain more. I think synchronized() can take a Thread object as argument.
Joined: Feb 28, 2007
The given code speaks loudly that the exception, that will be thrown is IllegalMonitorStateException. That is because, wait() method is called in the synchronized context; you first take lock of that object and then call wait method inside that block, and then release the lock.
Alright, Vasilli & Megha, you agree upto this?
I am only concerned about the question (picked from a reputed mock exam), It has several options and the given correct answer says IllegalStateException; There is no corelation between IllegalMonitorStateException and IllegalStateException;
IllegalStateException is thrown when you call a method on scanner reference when it is closed. java.util.Scanner scan = new java.util.Scanner(System.in); scan.nextInt(); scan.close(); scan.nextInt(); //IllegalStateException
But I am afraid of the bizarre answer of the original question posted by me on the top, regarding IllegalStateException.
Megha says, I think synchronized() can take a Thread object as argument.
Definitely synchronized() can take Thread object; It means no more than one thread can access that object at a time; I think this scenario in the following way:
i think, this code will throw java.lang.IllegalMonitorStateException: not IllegalStateException ... see, there are two things thread of execution and thread object having 1-1 mapping. A thread object is just like other java objects so it also has a lock and any thread can acquire it.but remember, a thread of execution never hold the lock of its thread object but it can acquire by calling synchronized block or method. that is the reason sometimes, run() is made synchronized.
so in the above code, the current thread (means,thread of execution) will try to acquire the lock of current thread (here, it is thread object) which is available. so no, IllegalStateException. but in the synchronized block you are calling wait on obj object whose lock is not acquired by thread(thread of execution) and throws IllegalMonitorStateException.