Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java JDBC efficiency: How long should a connection be maintained?

I'm still working on the same problem mention here. It seems to work fine especially after creating an AbstractModel class shown below:

public abstract class AbstractModel {

    protected static Connection myConnection = SingletonConnection.instance().establishConnection();
    protected static Statement stmt;
    protected static ResultSet rs;

    protected boolean loginCheck;                   // if userId and userLoginHistoryId are valid - true, else false
    protected boolean userLoggedIn;                 // if user is already logged in - true, else false

    public AbstractModel (int userId, Long userLoginHistoryId){
        createConnection();                                 // establish connection
            loginCheck = false;
        userLoggedIn = false;
        if (userId == 0 && userLoginHistoryId == 0){        // special case for login
            loginCheck = true;                              // 0, 0, false, false
            userLoggedIn = false;                           // set loginCheck to true, userLogged in to false
        } else {
            userLoggedIn = true;
            try{
                String query = "select \"user_login_session_check\"(" + userId + ", " + userLoginHistoryId + ");";
                System.out.println("query: " + query);
                stmt = myConnection.createStatement();
                rs = stmt.executeQuery(query);
                while (rs.next()){
                    loginCheck = rs.getBoolean(1);
                }
            } catch (SQLException e){
                System.out.println("SQL Exception: ");
                e.printStackTrace();
            }
        }

    }
    // close connection
    public void closeConnection(){
        try{
            myConnection.close();
        } catch (SQLException e){
            System.out.println("SQL Exception: ");
            e.printStackTrace();
        }

    }
    // establish connection
    public void createConnection(){
        myConnection = SingletonConnection.instance().establishConnection();
    }

    // login session check
    public boolean expiredLoginCheck (){
        if (loginCheck == false && userLoggedIn == true){
            closeConnection();
            return false;
        } else {
            return true;
        }
    }

}

I've already posted the stored procedures and Singleton Pattern implementation in the link to the earlier question above.

I'm under the impression that I don't need to close the connection to the database after each single data transaction, as it would just slow the application. I'm looking at about 30 users for this system I'm building, so performance and usability is important.

Is it correct to prolong the connection for at least 3-4 data transactions? Eg. Validation checks to user inputs for some form, or, something similar to google's auto-suggest ... These are all separate stored function calls based on user input. Can I use one connection instance, instead of connecting and disconnecting after each data transaction? Which is more efficient?

If my assumptions are correct (more efficient to use one connection instance) then opening and closing of the connection should be handled in the controller, which is why I created the createConnection() and closeConnection() methods.

Thanks.

like image 565
greatkalu Avatar asked Jun 26 '12 06:06

greatkalu


1 Answers

Your code should never depend on the fact, that your application is currently the only client to the database or that you have only 30 users. So you should handle database connections like files, sockets and all other kinds of scarce resources that you may run ouf of.

Thus you should always clean up after yourself. No matter what you do. Open connection, do your stuff (one or SQL statements) and close connection. Always!

In your code you create your connection and save it into a static variable - this connection will last as long as your AbstractModel class lives, probably forever - this is bad. As with all similar cases put you code inside try/finally to make sure the connection gets always closed.

I have seen application servers running ouf of connections because of web applications not closing connections. Or because they closed at logout and somebody said "we will never have more then that much users at the same time" but it just scaled a little to high.

Now as you have your code running and closing the connections properly add connection pooling, like zaske said. This will remedy the performance problem of opening/closing database connection, which truely is costly. On the logical layer (your application) you doesn't want to know when to open/close physical connection, the db layer (db pool) will handle it for you.

Then you can even go and set up a single connection for your whole session model, which is also supported by DBCP - this is no danger, since you can reconfigure the pool afterwards if you need without touching your client code.

like image 119
Tomasz Stanczak Avatar answered Oct 23 '22 11:10

Tomasz Stanczak