java - 当ExecutorService ThreadFactory返回null而不是thead时如何处理

标签 java multithreading executorservice

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

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

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

当 ExecutorService 在可调用对象上运行提交并且 ThreadFactory 返回 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();
}

最佳答案

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

RuntimeException非常适合通常不可恢复的情况。例如,无法连接到数据库就是其中一种情况的典型例子。基本上在这种情况下你想说的是:

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

即使接口(interface)没有声明

RuntimeException,也可以在方法实现中抛出它们。因此,您可以更新您的 ThreadFactory 实现以抛出 RuntimeException 而不是返回 null。您甚至可以创建一个特定的 RuntimeException 子类,以确保清楚应用程序中的错误是什么,例如FailedToInitialiseThreadException

关于java - 当ExecutorService ThreadFactory返回null而不是thead时如何处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41485991/

相关文章:

java - 无法读取 BroadcastReceiver 中的最后一条短信

java - 编译错误 : Type List can't be Generic

java - 在 1000 个线程中增加 Java 中的 AtomicInteger 不会生成值 1000

java - 我们是否在堆的 PermGen 区域中为所有原始类型提供了池?

java - Swing 应用程序框架 session 存储

c - 为什么 select() 不考虑超时,尤其是在多线程中

c# - 如何捕获线程执行中方法返回的值#

java - 优化多个文件的并行处理

java - 如果线程列表中的任何线程发生异常,则中断所有线程

java - 在 Java 中 : how can i terminate execution of all threads without waiting for them to finish their jobs using ExecutorService?