2008/04/24

Inter-thread coordination: wait, notify and interrupt

Just a sample code to test the inter-thread coordinating by using the object's wait and notify methods.

public class TestWaitAndNotify {
private final Object event = new Object(); private final Task1 task1 = new Task1(); private final Task2 task2 = new Task2(); private boolean stop; public TestWaitAndNotify() {
stop = false;
} public static void main(String[] args) throws InterruptedException {
TestWaitAndNotify twan = new TestWaitAndNotify(); twan.doIt();
} void doIt() throws InterruptedException {
task2.start(); task1.start(); stop = true; System.out.println("main:t [try to stop]"); synchronized (event){
System.out.println("main:t [notify all waiting threads]"); event.notifyAll();
} System.out.println("main:t [quit]");
} class Task1 extends Thread{
public void run(){
synchronized (event){
System.out.println("task1 running."); while(!stop){
System.out.println(">>>>>>>>task1 did"); event.notifyAll(); try {
System.out.println("task1 waiting."); event.wait(0); System.out.println("task1 wake");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
} System.out.println("task1 quit");
}
}
} class Task2 extends Thread{
public void run(){ synchronized (event){
System.out.println("Task2 running."); while(!stop){
try {
//Thread.sleep(10000); System.out.println("task2 waiting."); event.wait(0); System.out.println("task2 wake");
} catch (InterruptedException e) {
e.printStackTrace();
} System.out.println("<<<<<<<task2 did"); event.notifyAll();
} System.out.println("task2 quit");
} }
}
}
Conclusion:
  1. The order of threads starting is important in order to make sure the threads are waiting and notifying in sequence per our expectation.
  2. One object could be used as an event/signal to coordinate the threads behaviors by using wait and notify combination.
  3. Don't swallow or ignore the InterruptedException as you usually will do. Try to handle it properly, because someone might try to stop the blocking thread by interrupt it. Especially you are doing some common library which might be called by various unknown classes in various unknown conditions. Ignore it in your codes might cause other guy's attempts fail.
  4. Gracefully shutting down a thread by using an central control flag. However, a control thread or the main thread should try to call the coordinating object's notifyall before quit itself in order to wake up all the waiting threads and let them have a chance to shutdown gracefully.
  5. You can not always assume the call to the interrupt method of a blocking thread will work as your wish if you try to wake up it and let it quit. The probable failure case is:
    • If the blocking of thread is caused by waiting for the monitor of a synchronized method, it can not release the lock. However, if it's the case that the thread is waiting for a synchronized object, it's possible the interrupt will release the lock.
    • InterruptedException ignored by any codes is running in the thread when its interrupt is called.

4 comments:

manu said...

A new java/J2EE website develope by me please check it out
www.fabgabs.com and join the new social networking sensation with maps and videos

Anonymous said...

Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!

Anonymous said...

Рекомендую посетить сайт [url=http://theloveland.ru/]реальные знакомства[/url] Сайт входит в объединенный сервис знакомств, очень знаменитый в России , странах СНГ и Европе. Заходите, регистрируйтесь - здесь вас ждут приятные знакомства, романтические встречи и настоящая любовь!!!

Steve Smith said...

Great and Useful Article.

Online Java Training

Online Java Training from India

Online Java Training

Online Java Training From India

Java Training Institutes in Chennai

Java Training in Chennai

Well well... why another J2EE blog? I benefited from other people's technical blogs, and guess what, it's a good idea to contribute some of my works too. Hope it's helpful and useful, to all of your folks.