import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
+import java.util.NoSuchElementException;
/**
* {@link java.util.Iterator} applied to {@link java.sql.ResultSet}
private final ResultSet rs;
private final PreparedStatement stmt;
- private boolean didNext = false;
- private boolean hasNext = false;
+ private volatile boolean didNext = false;
+ private volatile boolean hasNext = false;
public ResultSetIterator(PreparedStatement stmt) throws SQLException {
this.stmt = stmt;
public boolean hasNext() {
if (!didNext) {
hasNext = doNextQuietly();
- didNext = true;
+ if (hasNext) {
+ didNext = true;
+ }
}
return hasNext;
}
@Override
@CheckForNull
public E next() {
- if (!didNext) {
- doNextQuietly();
+ if (!hasNext()) {
+ throw new NoSuchElementException();
}
- didNext = false;
try {
return read(rs);
} catch (SQLException e) {
throw new IllegalStateException("Fail to read result set row", e);
+ } finally {
+ hasNext = doNextQuietly();
}
}
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
+import java.util.NoSuchElementException;
import static org.fest.assertions.Assertions.assertThat;
import static org.fest.assertions.Fail.fail;
assertThat(iterator.next()).isEqualTo(30);
assertThat(iterator.hasNext()).isFalse();
+ try {
+ iterator.next();
+ fail();
+ } catch (NoSuchElementException e) {
+ // ok
+ }
+
iterator.close();
// statement is closed by ResultSetIterator
assertThat(stmt.isClosed()).isTrue();
iterator.remove();
fail();
} catch (UnsupportedOperationException ok) {
+ // ok
}
iterator.close();