Thursday, May 21, 2015

Java Thread Interruption With join() Method Explained

This is an example how Java thread interrupt() works with join() method. Suppose there are two threads, t1 & t2. So t2 calls join method on t1 from a method like below:
try {
     t1.join();
} catch (InterruptedException e) {
      System.out.println("INTERUPPTED!");
}
Now the question is when will code enter into catch block. Do you need to call interrupt() method on the calling thread which in this case is t2? Or do you need to to call interrupt() on the thread on which join is called which in this case is t1?

I have written a simple program that will clarify this.


public class TestInterrupt {
   
    public static void main(String[] args) {
         R2 r2 = new R2();
         Thread t2 = new Thread(r2);
         t2.start();
    }
   
    private static class R1 implements Runnable {
        public void run() {
            while(true) {
                System.out.println("do nothing!");
            }
        }
    }
    private static class R2 implements Runnable {
        public void run() {
            R1 r1 = new R1();
            Thread t1 = new Thread(r1);
            t1.start();
            t1.interrupt();
            try {
                t1.join();
            } catch (InterruptedException e) {
                System.out.println("INTERUPPTED!");
                System.exit(0);
            }
        }
    }

}

If you look at the above code, basically t2 calls t1.join() method and before that it calls t1.interrupt() method. Now if you run it, it will keep on printing "do nothing" in the console. So that means using interrupt on the thread on which join() is called is not working. Otherwise it would have exited the program.
Now run the below code:


public class TestInterrupt {
   
    public static void main(String[] args) {
         R2 r2 = new R2();
         Thread t2 = new Thread(r2);
         t2.start();
    }
   
    private static class R1 implements Runnable {
        public void run() {
            while(true) {
                System.out.println("do nothing!");
            }
        }
    }
    private static class R2 implements Runnable {
        public void run() {
            R1 r1 = new R1();
            Thread t1 = new Thread(r1);
            t1.start();
            Thread t2 = Thread.currentThread();
            t2.interrupt();
            try {
                t1.join();
            } catch (InterruptedException e) {
                System.out.println("INTERUPPTED!");
                System.exit(0);
            }
        }
    }

}

It calls t2.join(). And if you execute it, the code would exit after a few seconds after printing "INTERUPPTED!". So that's how it works. You need to interrupt the thread that is calling join() method on another thread and it will throw InterruptedException.

No comments:

Post a Comment