Q: Why should we use wait() method inside the try block?
You use a wait()
inside a synchronized
block or synchronized
method.
synchronized (this) {
while (!this.isTeapot) {
this.wait();
}
System.out.println("I am a teapot");
}
And in another method ...
synchronized (this) {
this.isTeapot = true;
this.notify();
}
Why?
- Because the spec says so.
- Because you will get an
IllegalMonitorStateException
if you don't.
But why?
- Because it is not possible to implement wait / notify condition variables safely without this restriction. The requirement is essential for thread safety; i.e. to avoid race conditions and memory anomalies.
The try
block is not mandatory. Use a try
block if you need to deal with an exception at that level. If not, allow it to propagate. This includes InterruptedException
... though since it is a checked exception, you would need to declare it in the method's throws
clause if you didn't catch it locally. But this is just normal Java exception handling. Nothing special.
For example:
try {
synchronized (this) {
while (!this.isTeapot) {
this.wait();
}
System.out.println("I am a teapot");
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
(For an explanation of the above example, see Why would you catch InterruptedException to call Thread.currentThread.interrupt()?.)
Q: Can we use wait() method outside the try block?
You cannot call wait()
outside of a synchronized
block or synchronized
method. (See above.)
The try
block is not mandatory. (See above.)