[BUG] Collections.unmodifiableMap(map).entrySet().iterator().forEachRemaining is missing null check

Rob Spoor openjdk at icemanx.nl
Sat Aug 6 16:12:19 UTC 2022


Hi,

I was working on upgrading another library of mine from Java 8 to 11, 
and I noticed my unit tests started failing. Some debugging traced the 
cause back to java.util.Collections$UnmodifiableMap$UnmodifiableEntrySet 
and its iterator() implementation.

In Java 8, the implementation only implemented hasNext, next and remove. 
It inherited forEachRemaining from java.util.Iterator, which first does 
a null check.

Since Java 11, the forEachRemaining is overridden:

public void forEachRemaining(Consumer<? super Map.Entry<K, V>> action) {
     i.forEachRemaining(entryConsumer(action));
}

The thing is, entryConsumer does not perform any null checks. That's 
done before entryConsumer is called in all occurrences but this one. The 
result is that a non-null action is passed to i.forEachRemaining, which 
causes the iterator to move forward before a NullPointerException is 
thrown. The solution is of course simple: add 
Objects.requireNonNull(action); to the method.

Rob


More information about the core-libs-dev mailing list