JAVAWarningRuntime ErrorMay 3, 2026

Runtime Error

java.util.concurrent.CancellationException: Programmatic interruption of task 'Thread-0' after 0.0 seconds

What This Error Means

This error occurs when a task is interrupted or cancelled before it has a chance to complete, typically due to a call to Thread.interrupt() or a call to ExecutorService.shutdownNow().

Why It Happens

This error happens because the current thread is interrupted while it's waiting for another thread to finish a task. This can occur when using ExecutorService and multiple threads are competing for resources. Additionally, it can also happen when using Java's built-in threading mechanisms and a thread is interrupted manually.

How to Fix It

  1. 1To fix this issue, ensure that any threads that may be interrupted are properly shutdown before attempting to interrupt another thread. Alternatively, use try-finally blocks to ensure that resources are cleaned up before thread interruption. In addition, consider using the ExecutorService's shutdown() method before calling shutdownNow() if you're using it for thread management.

Example Code Solution

❌ Before (problematic code)
Java
public class Main {
  public static void main(String[] args) throws InterruptedException {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(new Task());
    executor.shutdownNow();
  }
}

class Task implements Runnable {
  @Override
  public void run() {
    while (true) {}
  }
}
✅ After (fixed code)
Java
public class Main {
  public static void main(String[] args) throws InterruptedException {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<?> future = executor.submit(new Task());
    executor.shutdown(); // Instead of shutdownNow()
    future.get(); // Wait for the task to finish
  }
}

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

Fix for java.util.concurrent.CancellationException: Programmatic interruption of task 'Thread-0' after 0.0 seconds

Related JAVA Errors

Related JAVA Blog Articles

Have a different error? Get an instant explanation.

Explain Another Error