在线程池执行时抛出异常会对Thread发生什么影响?

时间:2017-06-15 15:44:51

标签: java multithreading threadpool

当一个线程在线程池执行时抛出异常会发生什么?

它会终止并被垃圾收集吗?

背景故事: 我经常使用ScheduledThreadPoolExecutor来运行任务,并且它也被Netty使用。现在,使用此应用程序的客户告诉我,他们有时会注意到一堆客户端随机断开连接,每次发生这种情况时,都会记录来自单独的非网络相关任务的堆栈跟踪。我的假设是Thread被中断并收集垃圾,因此Netty丢失了对该线程的任何引用并断开了分配的tcp客户端。

2 个答案:

答案 0 :(得分:6)

  

当一个线程在线程池执行时抛出异常会发生什么?

答案取决于代码是否使用threadPool.execute(...)threadPool.submit(...)。如果您正在使用execute(...)并且该任务抛出未捕获的异常,则该线程终止并且池会忘记该线程并在适当时立即启动另一个线程。任务和线程可以收集垃圾。

如果您正在使用submit(...),则任务将完成,将捕获异常,并且线程将继续运行并将提交给线程池的下一个作业出列并执行它。您可以通过扩展ThreadPoolExecutor并覆盖:

来查看引发的异常
protected void afterExecute(Runnable r, Throwable t) { }

使用submit(...)线程池捕获任务抛出的所有异常,以便它可以使用Future报告任务的状态。

  

它会终止并被垃圾收集吗?

如果使用execute(...),那么线程将终止,并且任务可以被垃圾收集。如果使用submit(...),则线程将不会终止,但任务可以被垃圾收集。现在有不同的方法,池可以决定减少在其中运行的线程数,这可能导致线程终止并可能被垃圾收集。

  

......一堆客户随机断开连接...

意味着什么东西在打扰他们?或者你想知道他们是否会抛出异常?如果一群人同时终止,似乎还会发生其他事情。

  

我的假设是线程被中断并且垃圾被收集,因此Netty丢失了对线程的任何引用并断开了分配的tcp客户端。

如果线程被中断,则有人在作业上调用cancel或正在关闭线程池。没有人应该打断线程。无论如何,这不会导致线程被终止和垃圾收集。如果线程被中断,那么任务当然可以继续运行,除非它抛出RuntimeException或其他东西。如果发生这种情况,一旦任务完成,线程池将清除中断,线程将从队列中提取下一个任务。

您可以使用以下代码查看异常处理:

public static void main(String[] args) {
    ExecutorService threadPool = Executors.newFixedThreadPool(1);
    // this thread will be killed and replaced
    threadPool.execute(new Task());
    // this thread will catch and handle the exception and run the following task
    threadPool.submit(new Task());
    threadPool.submit(new Task());
}

private static class Task implements Runnable {
    @Override
    public void run() {
        // this should print out the same thread ids even though the task threw
        System.out.println(Thread.currentThread().getId());
        throw new RuntimeException();
    }
}

答案 1 :(得分:0)

  

当一个线程在线程池执行时抛出异常会发生什么?

     

它会终止并被垃圾收集吗?

如果死的线程将线程池大小减小到小于核心池大小,则会立即创建一个新线程(因此您的旧线程可用于垃圾回收)

请参阅以下代码:

当我创建一个核心池大小=" 1" ,当我的运行线程抛出运行时异常时,立即创建了一个新线程。

当我创建一个核心池大小=" 2" ,当我的运行线程抛出运行时异常时,立即创建了一个新线程。

import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ThreadExample1 {


    private volatile ThreadPoolExecutor threadPoolExecutor;

    public static void main(String[] args) throws InterruptedException {
        ThreadExample1 threadExample1 = new ThreadExample1();
        threadExample1.doTheWork();
    }

    private void doTheWork() throws InterruptedException {
        Scanner scanner = new Scanner(System.in);


        ThreadFactory myThreadFactory = new MyThreadFactory("task");
        threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2, myThreadFactory);

        System.out.println("before task is sent to be executed:  thread pool size: " + threadPoolExecutor.getPoolSize() + ", core pool size: " + threadPoolExecutor.getCorePoolSize() + " - threads active count: " + threadPoolExecutor.getActiveCount());
        scanner.next();
        threadPoolExecutor.execute(new MyTask());

        System.out.println("immediately after task is sent to be executed: thread pool size: " + threadPoolExecutor.getPoolSize() + ", core pool size: " + threadPoolExecutor.getCorePoolSize() + " - threads active count: " + threadPoolExecutor.getActiveCount());
        scanner.next();

        System.out.println("going to sleep");
        Thread.sleep(2000);
        System.out.println("going to sleep");
        System.out.println("after waking up");
        System.out.println("after waking up: thread pool size: " + threadPoolExecutor.getPoolSize() + ", core pool size: " + threadPoolExecutor.getCorePoolSize() + " - threads active count: " + threadPoolExecutor.getActiveCount());
        scanner.next();

        threadPoolExecutor.shutdown();
        threadPoolExecutor.awaitTermination(5, TimeUnit.SECONDS);

    }

    class MyThreadFactory implements ThreadFactory {

        Logger logger = Logger.getLogger("MyThreadFactory");

        private int counter = 0;
        private String prefix = "";

        public MyThreadFactory(String prefix) {
            this.prefix = prefix;
        }

        @Override
        public Thread newThread(Runnable r) {
            counter++;
            String name = prefix + "-" + counter;
            logger.log(Level.WARNING, "thread: " + name + " - is going to be created");
            System.out.println("before a new thread is created. pool size: " + threadPoolExecutor.getPoolSize() + ", core pool size: " + threadPoolExecutor.getCorePoolSize() + " - threads active count: " + threadPoolExecutor.getActiveCount());
            return new Thread(r, name);
        }
    }


}


class MyTask implements Runnable {

    Logger logger = Logger.getLogger("MyTask");

    @Override
    public void run() {

        while (true) {

            System.out.println("thread: " + Thread.currentThread().getName() + " - current state: " + Thread.currentThread().getState());
            throw new RuntimeException("something bad happened");
        }

    }
}
相关问题