gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:00:18 24 4
gpt4 key购买 nike

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

我的问题是如何让 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com