Skip to content
What Happens When a Thread in a Java ThreadPool Throws an Exception?

What Happens When a Thread in a Java ThreadPool Throws an Exception?

This article examines how Java's ExecutorService thread pool reacts when a task throws an uncaught exception, comparing the behaviors of execute and submit methods, analyzing source code, and summarizing the impact on thread removal, creation, and exception retrieval.

JD Cloud Developers
JD Cloud Developers
JD Cloud Developers

1. When a thread in a thread pool throws an exception, how does the pool handle it?

We focus on java.util.concurrent.ExecutorService thread pools, analyzing via verification and source code reading.

2. Code verification

2.1 verify execute submission

2.1.1 Test code:

public class ThreadPoolExecutorDeadTest {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = buildThreadPoolExecutor();
        executorService.execute(() -> exeTask("execute"));
        executorService.execute(() -> exeTask("execute"));
        executorService.execute(() -> exeTask("execute-exception"));
        executorService.execute(() -> exeTask("execute"));
        executorService.execute(() -> exeTask("execute"));
        Thread.sleep(5000);
        System.out.println("再次执行任务=======================");
        executorService.execute(() -> exeTask("execute"));
        executorService.execute(() -> exeTask("execute"));
        executorService.execute(() -> exeTask("execute"));
        executorService.execute(() -> exeTask("execute"));
        executorService.execute(() -> exeTask("execute"));
    }

    public static ExecutorService buildThreadPoolExecutor() {
        return new ThreadPoolExecutor(5, 10, 30, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1000), new ThreadFactoryBuilder().setNameFormat("test-%s").build()
                , new ThreadPoolExecutor.CallerRunsPolicy());
    }

    private static void exeTask(String name) {
        String printStr = "[thread-name:" + Thread.currentThread().getName() + ",执行方式:" + name + "]";
        if ("execute-exception".equals(name)) {
            throw new RuntimeException(printStr + ", 我抛异常了");
        } else {
            System.out.println(printStr);
        }
    }
}

2.1.2 Execution result:

2.1.3 Conclusion:

When using execute , if the task throws an uncaught exception, the exception propagates, the thread is removed from the pool, and a new thread is created to replace it.

2.2 verify submit submission

2.2.1 Test code:

public class ThreadPoolExecutorDeadTest {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = buildThreadPoolExecutor();
        executorService.submit(() -> exeTask("execute"));
        executorService.submit(() -> exeTask("execute"));
        executorService.submit(() -> exeTask("execute-exception"));
        executorService.submit(() -> exeTask("execute"));
        executorService.submit(() -> exeTask("execute"));
        Thread.sleep(5000);
        System.out.println("再次执行任务=======================");
        executorService.submit(() -> exeTask("execute"));
        executorService.submit(() -> exeTask("execute"));
        executorService.submit(() -> exeTask("execute"));
        executorService.submit(() -> exeTask("execute"));
        executorService.submit(() -> exeTask("execute"));
    }

    public static ExecutorService buildThreadPoolExecutor() {
        return new ThreadPoolExecutor(5, 10, 30, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1000), new ThreadFactoryBuilder().setNameFormat("test-%s").build()
                , new ThreadPoolExecutor.CallerRunsPolicy());
    }

    private static void exeTask(String name) {
        String printStr = "[thread-name:" + Thread.currentThread().getName() + ",执行方式:" + name + "]";
        if ("execute-exception".equals(name)) {
            throw new RuntimeException(printStr + ", 我抛异常了");
        } else {
            System.out.println(printStr);
        }
    }
}

2.2.2 Execution result:

2.2.3 Conclusion:

When using submit , an uncaught exception does not propagate, no new thread is created, and the exception can be retrieved via Future.get().

3. Source code analysis

3.1 java.util.concurrent.AbstractExecutorService#submit(Runnable)

3.2 Execution logic of execute in ThreadPoolExecutor#runWorker

3.3 ThreadPoolExecutor#processWorkerExit

It shows that when an exception is thrown, the worker thread is removed and a new one is created.

3.4 Why does submit not create a new thread but reuse the original?

Submit wraps the Runnable in a RunnableFuture (FutureTask), which handles exceptions differently; the thread is not removed.

4. Summary

With execute , the exception stack trace is printed, the faulty thread is removed from the pool, and a new thread is created.

With submit , the exception stack trace is not printed, the thread remains in the pool, and the exception can be obtained via Future.get(). Neither method affects the execution of other threads in the pool.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaConcurrencyThreadPoolExecutorServiceExceptionHandling
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.