Site Search:

TaskRunnable.java

<Back

When your code calls a method that throws InterruptedException, then your method is a blocking method too, and must have a plan for responding to interruption. For library code, there are basically two choices:

  • Propagate the InterruptedException.
  • Restore the interrupt.

TaskRunnable.java restores the interrupted status by calling Thread.currentThread().interrupt() so as not to swallow the interrupt. Code higher up the call stack can see that an interrupt was issued, then took needed actions.

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class TaskRunnable implements Runnable {
    BlockingQueue<Task> queue = new LinkedBlockingQueue<>();

    public void run() {
        try {
            processTask(queue.take());
        } catch (InterruptedException e) {
            // restore interrupted status
            System.out.println(Thread.currentThread().getName());
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }

    void processTask(Task task) {
        // Handle the task
    }

    interface Task {
    }
    
    public static void main(String... args) {
        try {
            Thread a = new Thread(new TaskRunnable());
            a.start();
            Thread.sleep(5000);
            a.interrupt();
        } catch (InterruptedException e) {
            // won't reach here
            System.out.println(Thread.currentThread().getName());
            e.printStackTrace();
        } 
    }

}