--- old/src/java.base/share/classes/java/util/Collections.java 2016-12-06 13:21:16.000000000 -0800 +++ new/src/java.base/share/classes/java/util/Collections.java 2016-12-06 13:21:16.000000000 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -4699,8 +4699,8 @@ public void forEachRemaining(Consumer action) { Objects.requireNonNull(action); if (hasNext) { - action.accept(e); hasNext = false; + action.accept(e); } } }; --- old/test/java/util/Collections/SingletonIterator.java 2016-12-06 13:21:18.000000000 -0800 +++ new/test/java/util/Collections/SingletonIterator.java 2016-12-06 13:21:18.000000000 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,7 @@ /* * @test + * @bug 8024500 8166446 * @run testng SingletonIterator */ @@ -38,6 +39,16 @@ @Test(groups = "unit") public class SingletonIterator { + static void checkAtEnd(Iterator it) { + assertFalse(it.hasNext()); + try { + Object o = it.next(); + fail("Should throw NoSuchElementException at end"); + } catch (NoSuchElementException ex) { + // ignore; + } + } + public void testForEachRemaining() { Iterator it = Collections.singleton("TheOne").iterator(); AtomicInteger cnt = new AtomicInteger(0); @@ -48,13 +59,18 @@ }); assertEquals(cnt.get(), 1); - assertFalse(it.hasNext()); + checkAtEnd(it); + } + + static class SingletonException extends RuntimeException { } + + public void testThrowFromForEachRemaining() { + Iterator it = Collections.singleton("TheOne").iterator(); try { - String str = it.next(); - fail("Should throw NoSuchElementException at end"); - } catch (NoSuchElementException ex) { - // ignore; - } + it.forEachRemaining(s -> { throw new SingletonException(); }); + } catch (SingletonException ignore) { } + + checkAtEnd(it); } }