As I understand this is very common snippet for multithreading in Java.
boolean loaded = false;
Object lock = new Object();
public void block() {
synchronized (lock) {
while(!loaded)
lock.wait(); // Unhandled exception type InterruptedException
}
}
and in another thread
public void done () {
synchronized (lock) {
loaded = true;
lock.notify();
}
}
But I am not sure where I should put try and catch, I can surround whole synchronized block or only lock.wait()
? What is rule of thumb and does it really matter?
For handling is it okay to call Thread.currentThread().interrupt()
in this situation?
You might want to consider the article by Brian Goetz: Java theory and practice: Dealing with InterruptedException
In general, if you don't know what to do then don't do anything but let a caller code know that this method can be interrupted while waiting on a lock. You can do this by adding throws InterruptedException to a method signature.
If for some reason you are forced to add a try/catch block and handle the exception then Thread.currentThread().interrupt() will do but re-throwing it can be as suitable.