import java.util.ArrayList; import java.util.HashMap; import java.util.Spliterator; import java.util.function.Consumer; import java.util.function.UnaryOperator; /* * HashMap spliterator tryAdvance() encounters remaining elements after a * forEachRemaining() call. */ public class ObjSplitter { private final static int COUNT = 1000; // With smaller COUNT, error happens only intermittently // private final static int COUNT = 12; public static void main(String[] args) { HashMap map = new HashMap<>(); for (int i = 0; i < COUNT; i++) { String keyVal = new String("String" + i); map.put(keyVal, keyVal); } Spliterator splitter = map.keySet().spliterator(); // When loop covers more of the colleciton, the error seems to happen less often // for (int i = 0; i < COUNT / 2; i++) { // for (int i = 0; i < COUNT / 2 - 1; i++) { for (int i = 0; i < 10; i++) { splitter.tryAdvance(b -> System.out.println("tryAdvance: " + b)); } // finish it splitter.forEachRemaining(b -> System.out.println("forEachRemaining: " + b)); // Confirm there are no more elements splitter.forEachRemaining(b -> fail("forEachRemaining should have no elements: " + b)); splitter.tryAdvance(b -> fail("tryAdvance should have no elements: " + b)); } public static void fail(String msg) { throw new Error(msg); } }