如何处理ExecutorService ThreadFactory returns null 而不是thead的情况

How to deal with the situation when the ExecutorService ThreadFactory returns a null instead of a thead

我之前问过这个问题但无法再次打开它,因为我的更新没有启动重新打开过程。所以重新提交

我的问题是如何让 ExecutorService 立即意识到线程无效(空),而不必等待未来的获取。

我有一个用例,在 ThreadFactory 中创建线程时,如果无法正确设置线程(例如它无法连接到服务器),我想 return null。

当 ExecutorService 运行 在可调用对象上提交并且 ThreadFactory return 为 null 时,代码将 运行 但会在 future.get(5, TimeUnit.SECONDS);然后抛出 TimeoutException。问题是 ThreadFactory.newThread() 不允许我在这里抛出异常。

public class TestThreadFactory implements ThreadFactory {
    @Override
    public Thread newThread(Runnable r) {
        // try to create a conneciton that fails 
        // I cannot throw an exception here, so if there is a problem I have to  return null
        return null;
    }
}

public class ExecutorServicePool {

    public static ExecutorService getService() {
        return Executors.newFixedThreadPool(10, new TestThreadFactory());
    }
}

public static void main(String[] args) {
    ExecutorService executorService = ExecutorServicePool.getService();

    Callable callable = new Callable<String>() {
        @Override
        public String call() throws Exception {
            return "callable";
        }
    };

    Future<String> future = executorService.submit(callable);
    try {
        future.get(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    } catch (TimeoutException e) {
        e.printStackTrace();
    }
    executorService.shutdown();
}

您可以通过扩展 ThreadPoolExecutor 和

创建自定义执行器服务

根据需要重写调用 threadfactory 以获得新线程的方法。

你可以抛出一个 RuntimeException,这感觉是一件明智的事情。

RuntimeExceptions 非常适合通常无法恢复的情况。例如,无法连接到数据库就是其中一种情况的主要示例。基本上在这种情况下你想说:

"Something is really wrong and at the minute I can't process your request. Try again later"

RuntimeExceptions 可以在方法实现中抛出,即使接口没有声明它们。因此,您可以更新 ThreadFactory 实现以抛出 RuntimeException 而不是返回 null。您甚至可以创建一个特定的 RuntimeException sub-class 以确保清楚您的应用程序中的错误是什么,例如FailedToInitialiseThreadException