gpt4 book ai didi

java.util.ConcurrentModificationException 流

转载 作者:搜寻专家 更新时间:2023-10-31 08:16:21 29 4
gpt4 key购买 nike

我正在尝试以下代码 Java 8 SE我直接从 eclipse 运行它,它也有下面提到的异常我使用命令提示符运行它会产生相同的结果。

List<String> test = new ArrayList<>();
test.add("A");
test.add("B");
test.add("c");
test = test.subList(0, 2);
Stream<String> s = test.stream();
test.add("d");
s.forEach(System.out::println);

我不确定为什么会给出以下异常

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1388)
at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)

我运行的 Java 版本

java version "1.8.0_171"
Java(TM) SE Runtime Environment (build 1.8.0_171-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.171-b11, mixed mode)

最佳答案

最小代码

List<String> test = new ArrayList<>(Arrays.asList("java-8", "subList", "bug")).subList(0, 2);
Stream<String> stream = test.stream();
test.add("java-9");
stream.forEach(System.out::println); // any terminal operation

Java-8 [错误]

上面使用 Java-8 执行的代码会抛出 CME。根据javadoc of ArrayList

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

输出:

java-8
subList
Exception in thread "main" java.util.ConcurrentModificationException

问题

similar guidelines,下在迭代时修改集合被认为是编程错误,因此抛出 ConcurrentModificationException 是在“尽力而为”的基础上执行的。

但接下来的问题是,在上面的代码中,我们实际上是在集合迭代时或更确切地说之前修改了集合吗?

stream 不应该是惰性的吗?

在进一步搜索此类预期行为时,发现了类似的报告并作为错误修复 - ArrayList.subList().spliterator() is not late-binding这已在 Java-9 中修复。

与此相关的另一个错误 - ArrayList.subList().iterator().forEachRemaining() off-by-one-error

Java-11 [已修复]

虽然根据错误报告在 Java-9 中进行了修复,但我执行的实际测试是在 LTS 版本上进行的,上面共享的代码无一异常(exception)地工作。

输出:

java-8
subList
java-9

关于java.util.ConcurrentModificationException 流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53923668/

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