How to handle interruptions inside a Java thread?

Rishabh Agarwal
Javarevisited
Published in
6 min readMar 28, 2024

--

Tasks scheduled inside an application may often need to be cancelled. This can be because of several reasons such as,

  • Task failed to complete in a certain time and is now useless
  • Application is shutting down and all the existing tasks should be cancelled
  • Application is running low on memory and killing lower priority tasks is one way to free up memory
  • User requested cancellation for a task

Everything inside a Java application runs inside a thread. This may be the main thread, a user created thread, or a daemon thread. Thus, cancelling a tasks requires us to signal its executing thread to stop task execution. This signalling is where interruptions come into play.

But before we talk more about interruptions, let us try to brainstorm a solution on our own to fix this problem.

Naive Solution for Task Cancellation

Let us first create a runnable to model our task. This is how it may look.

public class Task implements Runnable {
@Override
public void run() {
while(true) {
executeTask();
}
}

void executeTask() {
// Task execution logic here
}
}

--

--

Rishabh Agarwal
Javarevisited

Software Developer 2 @ Schrödinger | IIT CSE Graduate - Writes about Software Engineering!