1

LinkedList Iterator next() は、hasNext() が true を返した後に呼び出された場合でも、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

アクセルが指摘したように、スレッド化の問題のようです。

このメソッドを作成するとどうなりますsynchronizedか?

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

次の可能性があります。

  1. lines別のスレッドから使​​用されます
  2. lines.next()呼ばれる// some more code...
  3. linesの別のインスタンスにバインドされています// some more code...
于 2013-06-21T11:37:21.307 に答える