简体   繁体   English

使用postgres和java执行sql查询时发生内存泄漏

[英]memory leak when executing sql query using postgres and java

I need to run some queries using java on postgres DB. 我需要在postgres DB上使用java运行一些查询。 The problem is when I execute a query using this code me memory increase and even I close the statement and the result set the memory still increasing. 问题是当我使用此代码执行查询时,内存增加,甚至我关闭了语句,结果集内存仍然增加。 Off course the GC will be executed, but the problem is that sometimes the GC is executed in the middle of a query execution and it change the time execution of my query. 当然,GC将被执行,但是问题是有时GC在查询执行的中间执行,这改变了查询的执行时间。 How I can solve this problem to prevent GC executing in the middle of SQL query and it is possible to prevent memory leak in my case? 如何解决此问题以防止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;
    }

The PostgreSQL JDBC driver snarfs the whole result set into RAM by default. PostgreSQL JDBC驱动程序默认将整个结果集存储到RAM中。

To change that, set the fetch size to a value different from 0. Then cursors will be used, and memory consumption should be stable. 要更改此设置,请将访存大小设置为不同于0的值。然后将使用游标,并且内存消耗应稳定。

From the documentation : 文档中

// make sure autocommit is off
conn.setAutoCommit(false);
Statement st = conn.createStatement();

// Turn use of the cursor on.
st.setFetchSize(50);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM