Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8166446

SingletonIterator.forEachRemaining doesn't advance before calling action

    XMLWordPrintable

    Details

      Description

      FULL PRODUCT VERSION :
      openjdk version "1.8.0_91"
      OpenJDK Runtime Environment (build 1.8.0_91-8u91-b14-3ubuntu1~16.04.1-b14)
      OpenJDK 64-Bit Server VM (build 25.91-b14, mixed mode)

      ADDITIONAL OS VERSION INFORMATION :
      Linux francescoUSB 4.4.0-36-generic #55-Ubuntu SMP Thu Aug 11 18:01:55 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

      The bug is OS indipendent

      A DESCRIPTION OF THE PROBLEM :
      In method "java.util.Collections.singletonIterator.forEachRemaining" if consumer throws RuntimeException the single elements is not consumed and may returned multiple times.

      Collections.java source code is: (line 4687)
                  public void forEachRemaining(Consumer<? super E> action) {
                      Objects.requireNonNull(action);
                      if (hasNext) {
                          action.accept(e); <--- swap these line
                          hasNext = false; <--- swap these line
                      }
                  }

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      See example code


      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------
      import java.util.*;

      public class Main {

          public static void main(String[] args) {
              Collection<String> elems = Collections.singleton("elem");
              //Collection<String> elems = Arrays.asList("elem"); // this works
              final Iterator<String> elemIterator = elems.iterator();
              try {
                  elemIterator.forEachRemaining((e) -> {
                      throw new RuntimeException();
                  });
              } catch (RuntimeException e) {
                  // manage exception
              }
              // elemIterator should be empty now
              System.out.println("Iterator is empty: " + elemIterator.hasNext()); // expected false
              System.out.println("next() method return void: " + elemIterator.next()); // expected NoSuchElementException
          }
      }

      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      Don't use Collection.singleton* methods

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              smarks Stuart Marks
              Reporter:
              webbuggrp Webbug Group
              Votes:
              0 Vote for this issue
              Watchers:
              7 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: