开发者

Java deque / prepared statement memory leak

开发者 https://www.devze.com 2022-12-08 15:39 出处:网络
One of the following pieces of code generates a memory leak, any idea which part? 1) private Deque<Snapshot> snapshots = new LinkedList<Snapshot>();

One of the following pieces of code generates a memory leak, any idea which part?

1)

private Deque<Snapshot> snapshots = new LinkedList<Snapshot>();

Iterator<Snapshot> i = world.getSnapshots().descendingIterator();
    while (i.hasNext()) {
        Snapshot s = i.next();
        if (curTime - s.getTimestamp() > 60000) {
            i.remove();
        } else {
            break;
        }
    }

2)

public static void initilizePreparedStatements() {
        try {
            insertNewReportRow = Instance.getWorld().getDB().getConnection().prepareStatement("INSERT INTO `rsca2开发者_StackOverflow中文版_reports` (`from`, `about`, `time`, `reason`, `snapshot_from`,`snapshot_about`,`chatlogs`, `from_x`, `from_y`, `about_x`, `about_y`) VALUES(?,?,?,?,?,?,?,?,?,?,?)");
        } catch (SQLException e) {
            e.printStackTrace();
            Logger.error(e);
        }
    }
    public synchronized static void submitReport() {
        /*removed*/
            try {
                    insertNewReportRow.setLong(1, from);
                    insertNewReportRow.setLong(2, about); 
                    insertNewReportRow.setLong(3, time); 
                    insertNewReportRow.setInt(4, reason);
                    insertNewReportRow.setString(5, snapshot_from);
                    insertNewReportRow.setString(6, snapshot_about);
                    insertNewReportRow.setString(7, chatlog);
                    insertNewReportRow.setInt(8, f.getX());
                    insertNewReportRow.setInt(9, f.getY());
                    insertNewReportRow.setInt(10, a.getX());
                    insertNewReportRow.setInt(11, a.getY());
                    insertNewReportRow.executeUpdate();
                } catch (SQLException e) {
                    e.printStackTrace();
                    Logger.error(e);
                } 
            }


My guess would be it's Instance.getWorld().getDB().getConnection() where you get a connection and only store a reference to the prepared statement it creates. This means you do not free the connection when your code is done with the prepared statement and the (assuming it comes from a connection pool) connection pool does not recycle the connection, but it will keep a reference to it in its maps.


Depending on implementation, breaking from iterator may cause the iterator to not complete itself and prevent itself from freeing tied resources and thus causing a memory leak. It's also possible you never clean your Deque either which causes linear growth in size over time.

0

精彩评论

暂无评论...
验证码 换一张
取 消