Reputation: 787
I am doing RPC's in GWT that query a database and I have a memory leak in my program and I have a strong suspicion its in the way I have the class set up. currently, I have to connect to the database within each method that I have and then close out that connection at the end of the method. Would doing it this way cause a memory leak? I feel like programming it this way leads to more code and is highly inefficient but I can't find many good samples to go off, can someone suggest a better way for this to work? names, IP's have been changed, and I've posted the connect method as a well as a sample of how the other method's are written.
public class DatabaseServiceImpl extends RemoteServiceServlet implements DatabaseService {
private Connection con = null;
String database = "ioma";
String host = "localhost";
String password = "foo";
String url = "jdbc:mysql://" + host + "/" + database;
String user = "foo";
public String connect() {
String connect = "";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
for (Throwable t : e)
System.err.println("Error connecting to the database: " + t);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
connect = "database connection aquired";
return connect;
}
public int getAssemblerCount() {
connect();
try {
int assemblerCount = 0;
String query = "SELECT COUNT(*) FROM assemblers";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
rs.next();
assemblerCount = rs.getInt(1);
rs.close();
ps.close();
con.close();
return assemblerCount;
} catch (SQLException e) {
for (Throwable t : e)
System.err.println("Database error in getAssemblerCount " + e);
return 0;
}
}}
Upvotes: 0
Views: 723
Reputation: 41127
You should always close in a "finally" block, so that the close happens in the event of an exception.
See the answers to this related question for help on doing that properly.
This is a common source of memory leaks and likely is your problem.
Upvotes: 1