LinkedList Iterator next() throwing NoSuchElementException even when called after hasNext() returning true

StackOverflow https://stackoverflow.com/questions/17234223

Question

LinkedList Iterator next() throwing NoSuchElementException even when called after hasNext() returning true.

Environment: Java 6 on Sun Solaris

Any idea why I'm hitting this exception on next() method call?

// lines is an instance of LinkedList
// writer is a FileWriter, Believe that is irrelevant to issue
while(lines.hasNext()){
    int i = 0;
    do {
            writer.write(lines.next());
            writer.newLine();
            i++;
    } while (lines.hasNext() && i < targetLineCount);
    // Some more code... 
}

Update with More Code

public class MyClass { // Only one instance of this class is used across application
    private List<String> master = new LinkedList<String>();
    // Other instance members to tune this instance behaviour

    public MyClass(){
        // Read Source & populate master
    }

    public boolean writeDataSlot(Writer writer, int targetLineCount){ // Can be called by different Threads
        Ierator<String> lines = master.iterator();
        while(lines.hasNext()){
            int i = 0;
            do {
                writer.write(lines.next());
                writer.newLine();
                i++;
            } while (lines.hasNext() && i < targetLineCount);
            // Some more code to populate slot from different source.
        }
    }
}
Was it helpful?

Solution

Seems like a threading issue, as Axel pointed out.

What happens if you make this method synchronized ?

public synchronized boolean writeDataSlot(Writer writer, int targetLineCount)

OTHER TIPS

I see these possibilities:

  1. lines is used from another thread
  2. lines.next() is called in // some more code...
  3. lines is bound to another instance in // some more code...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top