Java
Multithreading
Thread Interrupt
Concurrency
Programming Tips

Interrupt a sleeping Thread

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In Java, you do not forcibly wake a sleeping thread by killing it. The normal mechanism is interruption: one thread calls interrupt(), and the sleeping thread receives an InterruptedException and decides how to shut down or continue.

What interrupt() Actually Does

Each Java thread has an interrupt status. Calling thread.interrupt() sets that status. If the target thread is blocked in Thread.sleep(), Object.wait(), or Thread.join(), Java clears the status and throws InterruptedException instead.

That detail matters because interruption is cooperative. It is a request to stop what the thread is doing, not a guarantee that execution ends immediately.

Here is a minimal example with a sleeping worker:

java
1public class InterruptSleepingThread {
2    public static void main(String[] args) throws InterruptedException {
3        Thread worker = new Thread(() -> {
4            try {
5                System.out.println("Worker sleeping");
6                Thread.sleep(10_000);
7                System.out.println("Worker finished sleeping normally");
8            } catch (InterruptedException e) {
9                System.out.println("Worker interrupted while sleeping");
10                Thread.currentThread().interrupt();
11            }
12        });
13
14        worker.start();
15        Thread.sleep(1_000);
16        worker.interrupt();
17        worker.join();
18    }
19}

After about one second, the main thread interrupts the worker. The worker leaves sleep() immediately and enters the catch block.

Handle InterruptedException Correctly

The right response depends on the role of the thread.

If the thread should stop, the cleanest solution is usually to log if needed and return:

java
1class PollingTask implements Runnable {
2    @Override
3    public void run() {
4        while (true) {
5            try {
6                doWork();
7                Thread.sleep(500);
8            } catch (InterruptedException e) {
9                Thread.currentThread().interrupt();
10                return;
11            }
12        }
13    }
14
15    private void doWork() {
16        System.out.println("Polling external service");
17    }
18}

Notice the call to Thread.currentThread().interrupt(). When InterruptedException is thrown, the interrupted flag has already been cleared. Restoring it preserves the signal for higher-level code or for diagnostics.

If your method can declare throws InterruptedException, that is often even better. It lets the caller decide the shutdown policy instead of swallowing the signal.

Interrupting Threads That Are Not Sleeping

A compute-heavy loop will not throw InterruptedException on its own. It must check the interrupted status explicitly.

java
1public class InterruptBusyLoop {
2    public static void main(String[] args) throws InterruptedException {
3        Thread worker = new Thread(() -> {
4            long value = 0;
5            while (!Thread.currentThread().isInterrupted()) {
6                value += 1;
7            }
8            System.out.println("Stopped at value = " + value);
9        });
10
11        worker.start();
12        Thread.sleep(100);
13        worker.interrupt();
14    }
15}

This pattern is essential for CPU-bound work. If you never check isInterrupted(), the interrupt request is effectively ignored.

Executor Services and Cancellation

In real applications, threads are often managed through an ExecutorService rather than by creating Thread objects directly. In that model, interruption still matters because Future.cancel(true) sends an interrupt to the running task.

java
1import java.util.concurrent.*;
2
3public class ExecutorInterruptDemo {
4    public static void main(String[] args) throws Exception {
5        ExecutorService pool = Executors.newSingleThreadExecutor();
6
7        Future<?> future = pool.submit(() -> {
8            try {
9                while (true) {
10                    System.out.println("Working");
11                    Thread.sleep(1_000);
12                }
13            } catch (InterruptedException e) {
14                Thread.currentThread().interrupt();
15                System.out.println("Task cancelled");
16            }
17        });
18
19        Thread.sleep(1_500);
20        future.cancel(true);
21        pool.shutdown();
22    }
23}

That is why interruption-aware code is worth writing even when you are not manipulating raw threads.

Common Pitfalls

A common mistake is catching InterruptedException and doing nothing. That discards the cancellation request and makes shutdown unreliable.

Another error is assuming interrupt() forcefully stops any code path. It only has immediate effect when the thread is in an interruptible blocking call or when your code checks the flag.

Some developers also reach for deprecated mechanisms such as Thread.stop(). Do not use them. They can leave shared state inconsistent and are not a safe replacement for interruption.

Finally, avoid wrapping long loops in a broad catch (Exception e) block that hides InterruptedException. If interruption is part of your control flow, treat it explicitly.

Summary

  • Use thread.interrupt() to request that another thread stop waiting or stop soon
  • 'Thread.sleep() reacts by throwing InterruptedException'
  • Restore the interrupt status if you catch the exception and then exit or rethrow
  • Busy loops must check isInterrupted() themselves
  • 'Future.cancel(true) relies on the same interruption mechanism'

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.