简体   繁体   English

PreparedStatement导致OOM错误

[英]PreparedStatement causing OOM errors

I have a listener method that contains the following code. 我有一个包含以下代码的侦听器方法。 That method is called multiple times a second. 该方法每秒被调用多次。 It is, however, causing a memory leak within my application. 但是,它在我的应用程序中导致内存泄漏。

I think it may be with the way I am handling the prepared statement (creating new one for each object received). 我认为这可能与我处理预准备语句的方式有关(为每个收到的对象创建一个新语句)。 Am I doing anything obviously wrong? 我做了什么明显错误的事吗? Should I be setting the PS to null once it's used? 一旦使用PS,我应该将其设置为空吗? Are the PSs being retained for some reason? PS是否因某种原因被保留?

Also, I'm manually specifying the table name for the PS. 另外,我手动指定PS的表名。 Is that redefinition defeating the purpose of using a Prepared Statement entirely? 这种重新定义是否完全违背了使用预备声明的目的?

String text = object.getText();

//determineDb method determines the db for the object based on its content
ArrayList<Topic> toAddList = determineDatabase(text);
if (toAddList.size() > 0) {
    int epoch = (int) (System.currentTimeMillis() / 1000);
    //Topic class contains DB info, topic name and associated terms
    for (Topic a : toAddList) {
        try {
            pst = con
    .prepareStatement("INSERT INTO "
            + a.getTopic()
            + " (created, received, username, text, ignored, retweet, value) VALUES(?, ?, ?, ?, ?, ?, ?)");
            pst.setString(1, String.valueOf(object.getCreatedAt().getTime() / 1000));
            pst.setString(2, String.valueOf(epoch));
            pst.setString(3, object.getUser());
            pst.setString(4, text);
            pst.setInt(5, 0);
            pst.setInt(6, object.isOriginal() ? 1 : 0);
            pst.setDouble(7, otherClass.analyzeString(object.getText()));
            pst.executeUpdate();
        } catch (SQLException ex) {
            System.out.println(ex);
        }
    }
}

You must close your PreparedStatement after you use it, always in a finally block. 必须在使用后关闭PreparedStatement,始终在finally块中。 Any object in java which could correspond to an external resource should always be handled carefully (cleaned up as soon as it is no longer useful). 始终小心处理java中可能对应外部资源的任何对象(一旦不再有用就立即清理)。 All JDBC resources fall into this category (ResultSet,Statement,Connection). 所有JDBC资源都属于此类别(ResultSet,Statement,Connection)。

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

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