LinkedList Iterator next() 抛出 NoSuchElementException,即使在 has



LinkedList Iterator next(( 抛出 NoSuchElementException,即使在 hasNext(( 返回 true 之后调用也是如此。

环境: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.
        }
    }
}

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

如果将此方法设为synchronized会发生什么?

public synchronized boolean writeDataSlot(Writer writer, int targetLineCount)

我看到了这些可能性:

  1. 从另一个线程使用lines
  2. lines.next()// some more code...中被称为
  3. lines绑定到// some more code...中的另一个实例

相关内容

  • 没有找到相关文章

最新更新