Given:
void waitForSignal() {
Object obj = new Object();
synchronized (Thread.currentThread()) {
obj.wait();
obj.notify();
}
}
Which statement is true?
A.
This code can throw an InterruptedException.
B.
This code can throw an IllegalMonitorStateException.
C.
This code can throw a TimeoutException after ten minutes.
D.
Reversing the order of obj.wait() and obj.notify() might cause this method to complete normally.
E.
A call to notify() or notifyAll() from another thread might cause this method to complete normally.
F.
This code does NOT compile unless obj.wait() is replaced with ((Thread) obj).wait().
Explanation:
unreported exception java.lang.InterruptedException; must be caught or declared to be thrown
obj.wait();
^
1 error
I know that question is from the exam, but it’s quite wrong, at first the code doesn’t compile because the obj.wait() call is not surrounded by try{}catch{}. The error mentioned in the explaination is NOT an exception, it is the compile error.
Fixing the compile error, the code is going to throw an IllegalMonitorStateException because the lock acquired is on the wrong object.
That’s almost true; exercise is a little wrong, OK, the code doesn’t compile. But is because it “can throw an InterruptedException”, hence, correct answer is option A.
================================================
alvaro@alvaro:~/ws/TEST1/src$ javac TestThread.java
TestThread.java:7: error: unreported exception InterruptedException; must be caught or declared to be thrown
obj.wait();
^
================================================
The statement doesn’t specify that code must compile, just refer to a posibility, that can do something, and in fact, that’s it so.