I get a ConcurrentModificationException although the piece of code that is listed in the stacktrace doesn't do any modification:
Map<String, ProblemItem> problemItemsMap = getProblemItemsMap();
Optional<ProblemItem> findAny =
problemItemsMap.values().stream()
.filter(pi -> pi.getId().equals(id))
.findAny();
I understand from this answer that it has to do with the HashMap. But as you can see, there is no add or remove or any other modification on the map at this location. I assume the problem occurs because of a modification somewhere else that just happen to be at the same time as the iteration.
The stacktrace looks like this:
Uncaught exception in thread 'pool-10-thread-1'.java.util.ConcurrentModificationException: null
at java.base/java.util.HashMap$ValueSpliterator.tryAdvance(HashMap.java:1698)
at java.base/java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:127)
at java.base/java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:502)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:488)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:150)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.findAny(ReferencePipeline.java:548)
So I have no clue where the modification takes place and it confuses me that the stacktrace shows the iteration and not the modification.
It's worth mentioning that this exception only occurs once in a while in my multi thread application.
findAnyis just the method starting the whole stream evaluation || "as you can see"?!! not really - that for sure is not the whole code! Better post a minimal reproducible example. || documentation: "thrown by methods that have detected concurrent modification of an object when such modification is not permissible . . . it is not generally permissible for one thread to modify a Collection while another thread is iterating over it"