gpt4 book ai didi

Java forEach lambda 抛出并发修改异常

转载 作者:行者123 更新时间:2023-12-02 02:08:27 31 4
gpt4 key购买 nike

下面的方法抛出ConcurrentModificationException的原因可能是什么?

static Set<String> setOfAllocAccountsIn(final @NotNull Execution execution) {
final Set<String> allocAccounts = new HashSet<>();
execution.legs().forEach(leg -> leg.allocs().forEach(alloc -> {
if (alloc.account() != null) {
allocAccounts.add(alloc.account());
}
}));
return allocAccounts;
}

堆栈跟踪:

"java.util.ConcurrentModificationException:
at java.base/java.util.ArrayList.forEach(ArrayList.java:1382)
at com.client.stp.util.DealsBuilderUtil.setOfAllocAccountsIn(DealsBuilderUtil.java:146)
at com.client.stp.builder.GridDealsObjectBuilder.build(GridDealsObjectBuilder.java:47)
at com.client.stp.processor.DealToPDXMLTransformer.transform(DealToPDXMLTransformer.java:29)
at com.client.stp.processor.WorkPartitionerEngine.lambda$onEventSubmit$0(WorkPartitionerEngine.java:40)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:514)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.base/java.lang.Thread.run(Thread.java:844)

使用简单的for循环它工作得很好。该方法由多个线程使用其自己的执行对象副本调用。

使用简单 for 循环的解决方案:

 static Set<String> setOfAllocAccountsIn(final @NotNull Execution execution) {
final Set<String> allocAccounts = new HashSet<>();
for (final ExecutionLeg executionLeg : execution.legs()) {
for (final ExecutionAlloc executionAlloc : executionLeg.allocs()) {
if (executionAlloc.account() != null) {
allocAccounts.add(executionAlloc.account());
}
}
}
return allocAccounts;
}

我觉得它与静态方法及其由多个线程访问的局部变量有关,但根据理论,这将是线程局部变量并且不共享。给我一些时间来举一些简单的例子。

最佳答案

你的逻辑可以是这样的:

return execution.legs().stream()
.flatMap(leg -> leg.allocs().stream())
.map(executionAlloc -> executionAlloc.account())
.filter(Objects::nonNull)
.collect(Collectors.toSet());
  • 您正在 forEach 中使用 forEach(这里我将其替换为 flatMap)
  • 然后检查每个元素 alloc.account() 是否为 null(我将其替换为 filter)
  • 然后,如果条件正确,则将其添加到集合中(我将其替换为 collect)

关于Java forEach lambda 抛出并发修改异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50407133/

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