[英]Java SQL memory leak
我面临一个问题,我有一个 java 应用程序在服务器上运行,它开始在 memory 中增长,直到最终服务器无法再处理它。
这是某种 memory 泄漏/资源泄漏问题,由于垃圾收集,我认为这在 Java 中极为罕见。 我猜有些东西被引用并且从未使用过,所以垃圾收集器不会收集它。
问题是 memory 中的大小增长如此缓慢,以至于我无法正确调试它(可能需要两周时间才能使服务器无法使用)。 我正在使用 java + mysql-connector,我确信 memory 泄漏是由与数据库连接相关的某些原因引起的。
这是我连接到数据库的方式:
private static Connection connect(){
try {
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","client","password");
return conn;
}catch(SQLException ex){
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
return null;
}
}
public static Connection getConnection(){
try {
if (connection == null || connection.isClosed()) connection = connect();
return connection;
}catch (SQLException exception){
System.out.println("exception trying to connect to the database");
return null;
}
}
我在这里找不到任何可能的问题,但谁知道呢!
以下是我从数据库中检索信息的方法:
public void addPoints(long userId,int cantidad){
try {
if(DatabaseConnector.getConnection()!=null) {
PreparedStatement stm = DatabaseConnector.getConnection().prepareStatement("UPDATE users SET points = points + ? WHERE id = ? ");
stm.setLong(2, userId);
stm.setInt(1, cantidad);
if(stm.executeUpdate()==0){ //user doesn't have any point records in the database yet
PreparedStatement stm2 = DatabaseConnector.getConnection().prepareStatement("INSERT INTO users (id,points) VALUES (?,?)");
stm2.setLong(1, userId);
stm2.setInt(2, cantidad);
stm2.executeUpdate();
}
}
}catch (SQLException exception){
System.out.println("error recording points");
}
}
public ArrayList<CustomCommand> getCommands(long chatId) throws SQLException{
ArrayList<CustomCommand> commands = new ArrayList<>();
if(DatabaseConnector.getConnection() != null) {
PreparedStatement stm = DatabaseConnector.getConnection().prepareStatement("SELECT text,fileID,commandText,type,probability FROM customcommands WHERE chatid = ?");
stm.setLong(1, chatId);
ResultSet results = stm.executeQuery();
if(!results.isBeforeFirst()) return null;
while (results.next()){
commands.add(new CustomCommand(results.getString(1),results.getString(2),results.getString(3), CustomCommand.Type.valueOf(results.getString(4)),results.getInt(5)));
}
return commands;
}
return null;
}
也许问题与异常捕获和未正确执行的语句有关? 也许与结果集有关? 这让我疯狂。 谢谢你帮助我!
在返回之前,您无需清理ResultSet
和Statement
。 这是个坏主意。 您应该在finally
块中的单个 try/catch 块中关闭每个块。
ResultSet
是一个 object,它表示数据库上的数据库 cursor。 你应该关闭它,这样你就不会用完游标。
我不会有一个 static Connection
。 我希望有一个线程安全的托管连接池。
我不会返回 null。 您不清楚用户应该对此做什么。 最好抛出异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.