- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下代码:
ConcurrentHashMap taskMap= new ConcurrentHashMap();
....
taskMap.compute(key, (k, queue) -> {
CompletableFuture<Void> future = (queue == null)
? CompletableFuture.runAsync(myTask, poolExecutor)
: queue.whenCompleteAsync((r, e) -> myTask.run(), poolExecutor);
//to prevent OutOfMemoryError in case if we will have too much keys
future.whenComplete((r, e) -> taskMap.remove(key, future));
return future;
});
此代码的问题是,如果 future
已经完成 whenComplete
函数参数在与 compute
调用相同的线程中调用。在此方法的主体中,我们从 map 中删除条目。但计算方法文档禁止这样做,应用程序会卡住。
如何解决这个问题?
最佳答案
最明显的解决方案是使用 whenCompleteAsync
而不是 whenComplete
,因为前者保证使用提供的 Executor
执行操作,而不是调用线程。可以通过以下方式演示
Executor ex = r -> { System.out.println("job scheduled"); new Thread(r).start(); };
for(int run = 0; run<2; run++) {
boolean completed = run==0;
System.out.println("*** "+(completed? "with already completed": "with async"));
CompletableFuture<String> source = completed?
CompletableFuture.completedFuture("created in "+Thread.currentThread()):
CompletableFuture.supplyAsync(() -> {
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
return "created in "+Thread.currentThread();
}, ex);
source.thenApplyAsync(s -> s+"\nprocessed in "+Thread.currentThread(), ex)
.whenCompleteAsync((s,t) -> {
if(t!=null) t.printStackTrace(); else System.out.println(s);
System.out.println("consumed in "+Thread.currentThread());
}, ex)
.join();
}
这将打印类似的内容
*** with already completed
job scheduled
job scheduled
created in Thread[main,5,main]
processed in Thread[Thread-0,5,main]
consumed in Thread[Thread-1,5,main]
*** with async
job scheduled
job scheduled
job scheduled
created in Thread[Thread-2,5,main]
processed in Thread[Thread-3,5,main]
consumed in Thread[Thread-4,5,main]
所以你可以使用
taskMap.compute(key, (k, queue) -> {
CompletableFuture<Void> future = (queue == null)
? CompletableFuture.runAsync(myTask, poolExecutor)
: queue.whenCompleteAsync((r, e) -> myTask.run(), poolExecutor);
//to prevent OutOfMemoryError in case if we will have too much keys
future.whenCompleteAsync((r, e) -> taskMap.remove(key, future), poolExecutor);
return future;
});
如果提前完成的可能性很大,您可以使用以下方法减少开销
taskMap.compute(key, (k, queue) -> {
CompletableFuture<Void> future = (queue == null)
? CompletableFuture.runAsync(myTask, poolExecutor)
: queue.whenCompleteAsync((r, e) -> myTask.run(), poolExecutor);
//to prevent OutOfMemoryError in case if we will have too much keys
if(future.isDone()) future = null;
else future.whenCompleteAsync((r, e) -> taskMap.remove(key, future), poolExecutor);
return future;
});
也许,您没有找到这个明显的解决方案,因为您不喜欢依赖操作始终被安排为池中的新任务,即使完成已经发生在不同的任务中。您可以使用专门的执行程序来解决此问题,该执行程序只会在必要时重新安排任务:
Executor inPlace = Runnable::run;
Thread forbidden = Thread.currentThread();
Executor forceBackground
= r -> (Thread.currentThread()==forbidden? poolExecutor: inPlace).execute(r);
…
future.whenCompleteAsync((r, e) -> taskMap.remove(key, future), forceBackground);
但是您可能会重新考虑这种复杂的每个映射清理逻辑是否真的需要。它不仅很复杂,而且可能会产生显着的开销,可能会安排大量清理操作,而这些操作在执行时已经过时了,而这些操作并不是真正需要的。
执行起来可能会更简单、更高效
taskMap.values().removeIf(CompletableFuture::isDone);
不时清理整个 map 。
关于java - 如何防止 CompletableFuture#whenComplete 在上下文线程中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46034531/
我的应用程序中有 3 种不同的方法。全部返回CompletableFuture .我想并行执行方法 1 和 2。完成方法 1 和 2 后,我想使用方法 1 和 2 返回值的参数触发方法 3。 代码示例
我正在尝试加快对多个 API 的调用。 在下面的代码中,getFilteredEvents是当前同步版本。我有这样的感觉 map(x -> x.getFilteredEvents(eventResea
Q1。我的理解是,如果 future 正常或异常完成,就会调用 completableFuture.handle 。但是超时情况又如何呢? 第二季度。在哪里检查 completableFuture 的
我不明白这里发生了什么 CompletableFuture/supplyAsync。 如果我从先前实例化的 CompletableFuture 对象调用 supplyAsync 方法,它永远不会完成:
我有一个返回 CompletableFuture 的异步方法。 private CompletableFuture asyncA(..) 我公开了一个必须返回 CompleteableFuture 的
我在项目中找到了这段代码: int threadCount = 10; CompletableFuture[] futures = new CompletableFuture[threadCount]
让我们举个例子:我们有四种方法: CompletableFututre loadAndApply(SomeObject someObject); CompletableFuture loadData(
我有一个可完成的 future (future1),它创建了 10 个可完成的 future (futureN)。只有当所有 futureN 都完成时,有没有办法将 future1 设置为完成? 最佳
我想编写一个返回 CompletableFuture 的异步方法. future 的唯一目的是跟踪方法何时完成,而不是其结果。返回CompletableFuture会更好吗?或 Completable
我正在对我的数据库进行多次异步调用。我将所有这些异步调用存储在 List> list 上.我想一起收集所有结果,所以我需要等待所有这些调用完成。 一种方法是创建一个 CompletableFuture
我正在尝试使用 CompletableFuture 链接一些文件处理程序,它应该返回 CompletableFuture : CompletableFuture allGen = loadFile1(
我有 2 个 CompletableFuture。 task2 只能在 task1 完成后启动。然后,我需要等待所有任务完成。在下面的代码中,程序在 task1 结束后结束。 task2 开始但未完成
我有 2 个 CompletableFuture。 task2 只能在 task1 完成后启动。然后,我需要等待所有任务完成。在下面的代码中,程序在 task1 结束后结束。 task2 开始但未完成
我很难弄清楚这一点,并且可以向那些比我更有经验和知识的人寻求帮助。 基本问题是我需要获取对象列表,然后对于返回的每个对象,获取一些详细信息,并将详细信息缝合到对象中。我希望在这方面保持高效;我需要首先
我目前正在使用 CompletableFuture supplyAsync() 方法将一些任务提交到公共(public)线程池。这是代码片段的样子: final List>> completableF
为什么是CompletableFuture.allOf声明为 CompletableFuture而不是返回结果集合或其他东西?我认为制作 CompletableFuture.anyOf 是个好主意返回
我没有看到处理具有异步结果的异常的明显方法。 例如,如果我想重试一个异步操作,我会期待这样的事情: CompletionStage cf = askPong("cause error").handle
比如我有这样的方法: public CompletableFuture getPage(int i) { ... } public CompletableFuture getDocument(
我正在调用一个返回 CompletableFuture 的服务。 输出结构如下。 Class Output { public String name; public Integer a
我正在尝试转换 List>至CompletableFuture> .当您有许多异步任务并且需要获取所有这些任务的结果时,这非常有用。 如果其中任何一个失败,那么最终的 future 将失败。这就是我的
我是一名优秀的程序员,十分优秀!