Saturday, April 4, 2009

How to use SINGLETON pattern in a application to access Database?

This is sample code for accessing database by applying Singleton design pattern which is also thread safe because of eager initialization.

/*
Java class code for the above purpose.
*/
import java.sql.Connection;
import java.sql.DriverManager;

public class DBConf {
    private static Connection connection;
       
    static{
        try{
            String dbUrl = "jdbc:mysql://dbhost:dbport/dbname";
            String dbUname = "dbusername";
            String dbPword = "dbpassword";
            
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(dbUrl, dbUname, dbPword);
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }
    
    private DBConf(){}
    
    public static Connection getConnection(){
        return DBConf.connection;
    }
}

Look at the constructor which is defined as private so no one can instantiate it. The client can use the getConnection() method to get the Connection which is already eagerly loaded. This single connection can be used to access the Database by the whole application by not openning new connections.

Now a question comes, when to close the connection. My solution is just add a listener class to this application. 

/*
Add this code to your web.xml file. Please replace ] with > and [ with < in the following code.
*/

[listener]
        [listener-class]ApplicationWatch[/listener-class]
[/listener]

/*
Write the following class in your application default source directory.
*/
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;

public class ApplicationWatch implements ServletContextListener {
/* Application Startup Event */
public void contextInitialized(ServletContextEvent ce) {}

/* Application Shutdown Event */
public void contextDestroyed(ServletContextEvent ce) {
            try{
                DBConf.getConnection().close();
            }
            catch(Exception ex){
                ex.printStackTrace();
            }
        }
}

So, when the application will be destroyed (i.e. undeploying the application from the server) the connection will be closed.

Problems
1. This connection should be alive for the application lifetime. But the real scenario is, Database like MySQL shutdown the idle connection when it reaches its wait timeout, default is 8 hours.

But for, heavy hitted application for database connection, connection pooling is a better solution. Hope I will write about it in future.

Wish this article will help you. Thanks.