1

即使在 hasNext() 返回 true 之后调用 LinkedList 迭代器 next() 也会抛出 NoSuchElementException。

环境:Sun Solaris 上的 Java 6

知道为什么我在 next() 方法调用中遇到此异常吗?

// 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... 
}

更新更多代码

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.
        }
    }
}
4

2 回答 2

0

我看到了这些可能性:

  1. lines从另一个线程使用
  2. lines.next()被调用// some more code...
  3. lines绑定到另一个实例// some more code...
于 2013-06-21T11:37:21.307 回答
0

正如 Axel 指出的那样,这似乎是一个线程问题。

如果你做这个方法会发生什么synchronized

public synchronized boolean writeDataSlot(Writer writer, int targetLineCount)
于 2013-06-21T12:29:26.433 回答