3

I am using static variables pretty much heavily in my application. Now after the application status is finished I am facing a problem in garbage collection. The variables that are declares as static are never garbage collected and my memory runs out quickly.

The specific problem is on mysql connection. I am storing the connection variable in a static variable and so I don't have to open the connection every time I run a query. This leads to a problem of usage of all memory every time I use the connection variable to execute the query and the used memory is not released. Is it a good idea to store the connection variable in static variable ? when I tried to open and close the connection every time without static variable I solved the memory management problem but the responsiveness of the application is slowed down by 10 to 20 times.

Do you need more information to understand this problem ? If yes please ask me without down voting. Thanks!

EDIT This is my connector class

import java.sql.*;

public class connect {

    public Connection conn = null;

    public connect() {
        try {
            if (conn == null) {
                String userName = "root";
                String password = "password";               
                String url = "jdbc:mysql://localhost/pos?zeroDateTimeBehavior=convertToNull";                
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                conn = DriverManager.getConnection(url, userName, password);               
                System.out.println("Database connection established");               
            }
        } catch (Exception e) {
            System.err.println("Cannot connect to database server");           
        }
    }
}

This is my class where i am storing the connection

public class variables {
    public static connect con = new connect();
}

And this method i use to execute the query

public class mysql_query {
public static ResultSet execute_mysql(Connection con, String sqlStatement) {
        try {
            //ResultSet result = null;
            java.sql.Statement cs = con.createStatement();
            ResultSet result = cs.executeQuery(sqlStatement);
            return result;
        } catch (SQLException ex) {
            Logger.getLogger(mysql_query.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }

    }

 public static void main(String args[]){
     String sql = "SELECT * FROM pos_user_login WHERE moderator='1' AND "
                    + "company_id='1'";

     ResultSet rs = execute_mysql(variables.con.conn, sql);
  }
}
8
  • To clarify: Are you using the same connection object to perform all the queries in your application? What specific connection class are you using? Aug 30, 2011 at 7:27
  • Hard to say. Can you describe your application? Is it a batch job? A swing application? A web application? A standalone server where you can connect to using sockets? etc...
    – Lukas Eder
    Aug 30, 2011 at 7:27
  • @Lukas Eder: Its a swing application
    – Deepak
    Aug 30, 2011 at 7:29
  • When you say "open the connection every time" you want to mean "do a new connection object every time"? Aug 30, 2011 at 7:29
  • 2
    From your posted code, it seems pretty clear that you're not properly closing your resources... See an example of how to do that in my answer...
    – Lukas Eder
    Aug 30, 2011 at 7:42

4 Answers 4

5

Just an idea: You might not be closing your ResultSet and Statement objects, correctly. If you don't do that, the MySQL JDBC driver might keep a hold on many resources that you don't need anymore. Especially ResultSet can be very painful, as some parts of the database cursor are still in memory.

An example to give you an idea is this:

PreparedStatement stmt = null;
ResultSet rs = null;

try {
    stmt = connection.prepareStatement(...);
    rs = stmt.executeQuery();
}

// Close your resources in a finally block! Because the finally block
// is executed even if you have exceptions in the try block.
// If you do this a lot of times, write utility methods...
finally {
    try {
        if (rs != null) {
            rs.close();
        }
    } catch (SQLException ignore) {}

    try {
        if (stmt != null) {
            stmt.close();
        }
    } catch (SQLException ignore) {}
}
4
  • So just looking at your example and the edit i have added probably tat might be the cause!!! am i right ??
    – Deepak
    Aug 30, 2011 at 7:43
  • 1
    I'm pretty sure it is. Not closing those resources is a very common memory leak
    – Lukas Eder
    Aug 30, 2011 at 7:44
  • so do i have to use connection pool still to solve the problem ??
    – Deepak
    Aug 30, 2011 at 7:45
  • As Michael says, with connection pools, you're not using less memory. It's easier to handle the lifecycle of connections when you have lots of threads accessing the database (e.g. in a web server). But in your case, connection pools probably won't be necessary. At least not for the memory problem at hand
    – Lukas Eder
    Aug 30, 2011 at 7:50
5

Maybe it'd be better to look at using a connection pool rather than the static variable... Connection pools maintain a bunch of open connections and serve them out when they're needed. Should solve your performance problem and your memory problem.

4
  • So does tat mean i should get rid of the static variables and use connection pool ??
    – Deepak
    Aug 30, 2011 at 7:31
  • If it's a Swing application with just one thread accessing the database, a single connection is enough. Having several connections won't use less memory than having just one. But I don't see how a single connection object could use the whole memory.
    – JB Nizet
    Aug 30, 2011 at 7:34
  • @JB Nizet: actually every time i execute a query the objects are created. I have no idea why tat happens. I have added the code if you can have a look and tell me what it is I will be pleased.
    – Deepak
    Aug 30, 2011 at 7:41
  • @Deepak: Look at Lukas Eder's answer.
    – JB Nizet
    Aug 30, 2011 at 7:45
0

a static variable will not garbage collected but if you are just storing a some connection data it should not be a problem. What are you exactly storing?

Matteo

0

Well, judging by what you say, you have an object (let's call it Obj) class which contains the static variable with the connection. Due to you creates a new Obj each time and you stores it at that moment, I think you are doing a lot of copies of the connection which the JVM is unable to clean because they are static.

You could consider the possibility of store this kind of information in a Model class, or remove the static mark in order to let the JVM collect this objects properly.

2
  • can you point out the line where i am creating new objects every time!! tats where i am lost!! thanks!!
    – Deepak
    Aug 30, 2011 at 7:45
  • Well, you create a new connection when you creates a new variables object. If you call once time in all execution to this constructor, my answer lost importance, but if you are calling it ervery time, then, here is where you are creating a lot of connection objects. This is not necessary bad, but if you do it, you must close the resources (like @Lukas Eder does in his code) Aug 30, 2011 at 9:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.