How does Java Executor Framework handle task interruption, and what are the best practices for managing interruptions in tasks?

The Executor Framework supports task interruption by propagating interruption requests to running threads. When a task is interrupted, the thread's interrupted status is set, allowing the task to detect the signal and terminate gracefully. Proper interruption handling is essential for responsive, resource-efficient, and well-behaved concurrent applications.

Key Points: • Tasks should periodically check the interrupted status using isInterrupted() or respond to InterruptedException. • Future.cancel(true) can be used to request interruption of a running task submitted to an ExecutorService. • Long-running tasks should release resources, perform cleanup, and exit gracefully when interrupted.

Example: Consider a file-processing service that scans large files. If the user cancels the operation, the task should stop processing, close open files, release resources, and terminate instead of continuing unnecessary work.

Code Example:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class InterruptionExample {

    public static void main(String[] args) throws Exception {

        ExecutorService executor =
                Executors.newSingleThreadExecutor();

        Future<?> future = executor.submit(() -> {

            try {

                while (!Thread.currentThread().isInterrupted()) {

                    System.out.println("Processing...");
                    Thread.sleep(1000);
                }

            } catch (InterruptedException e) {

                Thread.currentThread().interrupt();
                System.out.println("Task interrupted");
            }
        });

        Thread.sleep(3000);

        future.cancel(true);

        executor.shutdown();
    }
}

Interview Tip: A concise interview answer is: The Executor Framework handles interruption through thread interruption signals. Tasks should regularly check their interrupted status, properly handle InterruptedException, clean up resources before exiting, and can be interrupted using Future.cancel(true). Following these practices ensures responsive and reliable task execution.