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.
}
}
}
答案 0 :(得分:0)
我看到了这些可能性:
lines
用于其他线程lines.next()
中调用// some more code...
lines
绑定到// some more code...
答案 1 :(得分:0)
正如Axel指出的那样,似乎就像一个线程问题。
如果您使用此方法synchronized
会怎样?
public synchronized boolean writeDataSlot(Writer writer, int targetLineCount)