JDK 19 ShutdownOnFailure 作用域还允许使用 shutdown 方法显式取消所有任务。 我怎么知道示波器是否已关闭? API 包括一个 isShutdown 方法,但它是私有(private)的。
这里有一些(不完整的)代码只是为了说明一种可能的用途,其中范围在所有者调用 shutdown 启动后的某个时间被取消。
我猜想在 join() 之后我可以发出另一个 scope.fork() 并检查是否将 future 返回到已取消的任务,但这看起来很奇怪。这是要走的路吗?
ExecutorService executor = Executors.newCachedThreadPool();
try (StructuredTaskScope.ShutdownOnFailure scope = new StructuredTaskScope.ShutdownOnFailure()) {
Future<Integer> numOrders = scope.fork(Business::getNumItemsFromRequest);
Future<Double> price = scope.fork(Business::getPriceFromDB);
Business.sleepFor(500);
scope.shutdown(); // cancels all the scope tasks
//numOrders.cancel(true); // cancel just one task
scope.join(); // wait for all tasks
try {
scope.throwIfFailed();
// how would I know if scope was shutdown before all tasks completed?
System.out.println("Scope Completed Without Errors ( But possibly canceled ) ");
double amount = numOrders.get() * price.get();
最佳答案
建议:将您需要的功能封装在子类中。
来自孵化器文档:
Extending StructuredTaskScope
StructuredTaskScope can be extended, and the handleComplete overridden, to implement policies other than those implemented by ShutdownOnSuccess and ShutdownOnFailure. The method may be overridden to, for example, collect the results of subtasks that complete with a result and ignore subtasks that fail. It may collect exceptions when subtasks fail. It may invoke the shutdown method to shut down and cause join to wakeup when some condition arises.
A subclass will typically define methods to make available results, state, or other outcome to code that executes after the join method. A subclass that collects results and ignores subtasks that fail may define a method that returns a collection of results. A subclass that implements a policy to shut down when a subtask fails may define a method to retrieve the exception of the first subtask to fail.
关于java - 我如何知道 Java 19 结构化并发 StructuredTaskScope 是否关闭(取消)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74464598/