Java中List.addAll方法导致ConcurrentModificationException异常,而没有任何循环。

huangapple go评论77阅读模式
英文:

Java ConcurrentModificationException on List.addAll method without any looping

问题

我遇到了ConcurrentModifcationException异常,在以下代码片段中,根据我阅读的有关错误原因的内容(在迭代器打开的情况下修改某些内容)这是没有道理的:

List<Field> kibanaFields = Arrays.asList(KibanaRow.class.getSuperclass().getDeclaredFields());
kibanaFields.addAll(Arrays.asList(KibanaRow.class.getDeclaredFields()));

发生在第二行。
我不理解这个...即使第一行内部实现了一些迭代器,在它返回的时候应该已经关闭了,然后才会运行第二个方法。

这里的目的是获取字段名称的列表,然后稍后在KibanaRow的每个字段上添加@JsonProperty注解的值。

英文:

I have the ConcurrentModifcationException raised, on the following snippet, which does not make sense based on what I read on what causes this error (modifying something you have an open iterator over):

	List&lt;Field&gt; kibanaFields = Arrays.asList(KibanaRow.class.getSuperclass().getDeclaredFields());
	kibanaFields.addAll(Arrays.asList(KibanaRow.class.getDeclaredFields()));

Second line, is where it happens.
I don't understand this.. even if the first line had some iterator implemented inside, it should have been closed by the time it returns and second method runs.

The purpose here, is to get a list of field names, and later on add the value of @JsonProperty annotation, on each of the KibanaRow's fields.

答案1

得分: 1

我不明白 CME 的特定原因。如果您展示给我们堆栈跟踪,我们或许能够找出问题所在...

然而,无论如何,您所尝试的做法将不起作用

List<Field> kibanaFields 
        Arrays.asList(KibanaRow.class.getSuperclass().getDeclaredFields());

这会创建一个由数组支持的列表。列表的大小是固定的,不能添加或删除元素。

kibanaFields.addAll(Arrays.asList(KibanaRow.class.getDeclaredFields()));

如果KibanaRow.class.getDeclaredFields()返回一个非空数组,这将尝试向kibanaFields添加更多元素。但实际上不能。应该会引发异常。

解决我所识别出的问题的一个方法是将asList结果的内容复制到一个新的ArrayList中;例如:

List<Field> kibanaFields = new ArrayList<>(Arrays.asList(...));
英文:

I don't understand the particular reason for a CME. If you showed us the stacktrace we may be able to work it out ....

However what you are trying to do will not work anyway:

List&lt;Field&gt; kibanaFields 
        Arrays.asList(KibanaRow.class.getSuperclass().getDeclaredFields());

This creates a list backed by an array. The list's size is fixed. Elements cannot be added or removed.

kibanaFields.addAll(Arrays.asList(KibanaRow.class.getDeclaredFields()));

If KibanaRow.class.getDeclaredFields() returns a non-empty array, then this will attempt to add more elements to kibanaFields. It can't. An exception should ensue.

One solution to the problem I have identified is to copy the asList result's contents into a new ArrayList; e.g.

List&lt;Field&gt; kibanaFields = new ArrayList&lt;&gt;(Arrays.asList(....));

huangapple
  • 本文由 发表于 2020年4月10日 10:37:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/61133210.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定