我需要在 postgres DB 上使用 java 运行一些查询。问题是,当我使用此代码执行查询时,内存会增加,即使我关闭语句,结果集内存仍然会增加。当然GC会被执行,但问题是有时GC会在查询执行的中间执行,它会改变我的查询的执行时间。我怎样才能解决这个问题,以防止GC在SQL查询中间执行,并且在我的情况下可以防止内存泄漏?
public long getStatementExecutionTimeInMilliseconds( final String sqlQuery,
final int fetchSize, final boolean fetchAttributesFlag,
Integer numberOfSelectedFields) throws SQLException {
Statement stmt = null;
ResultSet rs = null;
int numberOfResult = 0;
if (numberOfSelectedFields == null) {
numberOfSelectedFields = getNumberOfSelectedFields(sqlQuery);
}
long start = 0;
try {
stmt = createStatement (fetchSize);
stmt.executeQuery (sqlQuery);
start = System.currentTimeMillis ();
rs = stmt.executeQuery (sqlQuery);
while (rs.next ()) {
if (fetchAttributesFlag) {
for (int i = 1; i <= numberOfSelectedFields; i++) {
rs.getInt (i);
}
}
}
stmt.close ();
}
finally {
DatabaseUtils.tryClose(rs);
DatabaseUtils.tryClose(stmt);
}
//System.out.println (numberOfResult);
final long executionTimeInMilliseconds = System.currentTimeMillis() - start;
return executionTimeInMilliseconds;
}
最佳答案
默认情况下,PostgreSQL JDBC 驱动程序会将整个结果集捕获到 RAM 中。
要改变这一点,请将获取大小设置为不同于 0 的值。然后将使用游标,并且内存消耗应该稳定。
// make sure autocommit is off
conn.setAutoCommit(false);
Statement st = conn.createStatement();
// Turn use of the cursor on.
st.setFetchSize(50);
关于java - 使用postgres和java执行sql查询时内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57695211/