Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program continues to run despite InterruptedException

I started learning java and I am now at the concurrency chapter. After reading some stuff about concurrency I tried an example of my own.

public class Task implements Runnable{

public void run() {
    while(!Thread.interrupted()) {
        try {
            System.out.println("task");
            TimeUnit.SECONDS.sleep(2);
        }catch (InterruptedException e) {
            System.out.println("interrupted");
        }
    }
}

}

public static void main(String[] args) throws Exception {
    ExecutorService exec = Executors.newCachedThreadPool();
    exec.execute(new Task());
    TimeUnit.SECONDS.sleep(10);
    exec.shutdownNow();
}

The problem is that i was expecting to see the following output:

task
task
task
task
task
interrupted

but after I get this, the program continues printing until I close it.
So, my question is what am I doing wrong? why does the program continues printing?

like image 776
Daniel S. Avatar asked Aug 12 '11 17:08

Daniel S.


1 Answers

When you shutdown the executor, it tries to stop its running tasks by interrupting them. This causes an InterruptedException to be thrown, but you just swallow it and continue. You should return in your catch clause, and/or reset the interrupted status of the thread by calling Thread.currentThread.interrupt(), which will reset the interrupted status and exit the loop.

like image 192
JB Nizet Avatar answered Nov 03 '22 04:11

JB Nizet