// DBRatingsSource.java import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBRatingsSource { public DBRatingsSource() throws SQLException { DBConnection myConn = new DBConnection(); myConn.getConn().setReadOnly(true); // Optimization hint // Tell MySQL to return results one row at a time Statement stmt = myConn.getConn().createStatement( java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY); stmt.setFetchSize(Integer.MIN_VALUE); ResultSet rs = stmt.executeQuery("SELECT userId, movieId, rating FROM user_rating_pairs"); // ** BUG: myConn is garbage collected, and the DB connection is closed // during this long loop: //int i = 0; while (rs.next()) { //System.out.println(i++); } rs.close(); // Uncommenting this makes the bug go away, because myConn is // not garbage collected //System.out.println(myConn); } public static void main(String args[]) throws java.sql.SQLException { DBRatingsSource source = new DBRatingsSource(); } }