Thursday, July 28, 2011

Connection Pooling Example in Java with MySQL, Oracle, DB


ConnectionPool.java

package com;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Vector;

public class ConnectionPool implements Runnable
{    
    // Number of initial connections to make.
    private int m_InitialConnectionCount = 5;    
    // A list of available connections for use.
    @SuppressWarnings("rawtypes")
private Vector m_AvailableConnections = new Vector();
    // A list of connections being used currently.
    @SuppressWarnings("rawtypes")
private Vector m_UsedConnections = new Vector();
    // The URL string used to connect to the database
    private String m_URLString = null;
    // The username used to connect to the database
    private String m_UserName = null;    
    // The password used to connect to the database
    private String m_Password = null;    
    // The cleanup thread
    private Thread m_CleanupThread = null;
       
                                             
    //Constructor
    @SuppressWarnings("unchecked")
public ConnectionPool(String urlString, String user, String passwd) throws SQLException
    {
        // Initialize the required parameters
        m_URLString = urlString;
        m_UserName = user;
        m_Password = passwd;

        for(int cnt=0; cnt<m_InitialConnectionCount; cnt++)
        {
            // Add a new connection to the available list.
            m_AvailableConnections.addElement(getConnection());
        }
       
        // Create the cleanup thread
        m_CleanupThread = new Thread(this);
        m_CleanupThread.start();
    }    
   
    private Connection getConnection() throws SQLException
    {
        return DriverManager.getConnection(m_URLString, m_UserName, m_Password);
    }
   
    @SuppressWarnings("unchecked")
public synchronized Connection checkout() throws SQLException
    {
        Connection newConnxn = null;
       
        if(m_AvailableConnections.size() == 0)
        {
            // Im out of connections. Create one more.
             newConnxn = getConnection();
            // Add this connection to the "Used" list.
             m_UsedConnections.addElement(newConnxn);
            // We dont have to do anything else since this is
            // a new connection.
        }
        else
        {
            // Connections exist !
            // Get a connection object
            newConnxn = (Connection)m_AvailableConnections.lastElement();
            // Remove it from the available list.
            m_AvailableConnections.removeElement(newConnxn);
            // Add it to the used list.
            m_UsedConnections.addElement(newConnxn);            
        }        
       
        // Either way, we should have a connection object now.
        return newConnxn;
    }
   

    @SuppressWarnings("unchecked")
public synchronized void checkin(Connection c)
    {
        if(c != null)
        {
            // Remove from used list.
            m_UsedConnections.removeElement(c);
            // Add to the available list
            m_AvailableConnections.addElement(c);        
        }
    }            
   
    public int availableCount()
    {
        return m_AvailableConnections.size();
    }
   
    public void run()
    {
        try
        {
            while(true)
            {
                synchronized(this)
                {
                    while(m_AvailableConnections.size() > m_InitialConnectionCount)
                    {
                        // Clean up extra available connections.
                        Connection c = (Connection)m_AvailableConnections.lastElement();
                        m_AvailableConnections.removeElement(c);
                       
                        // Close the connection to the database.
                        c.close();
                    }
                   
                    // Clean up is done
                }
               
                System.out.println("CLEANUP : Available Connections : " + availableCount());
               
                // Now sleep for 1 minute
                Thread.sleep(60000 * 1);
            }    
        }
        catch(SQLException sqle)
        {
            sqle.printStackTrace();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}


Main.java

package com;

import java.sql.*;


public class Main
{
    public static void main (String[] args)
    {    
        try
        {
        //JDBC Driver for MySql Database
           // Class.forName("com.mysql.jdbc.Driver").newInstance();
       
        //JDBC Driver for Oracle Database
        Class.forName("oracle.jdbc.OracleDriver");
        }
        catch (Exception E)
        {
            System.err.println("Unable to load driver.");
            E.printStackTrace();
        }

        try
        {        
            //Connection with MySQL Database....
        //ConnectionPool cp = new ConnectionPool("jdbc:mysql://localhost/test", "root", "vinay0809");
           
       //Connection with Oracle Database...
        ConnectionPool cp = new ConnectionPool("jdbc:oracle:thin:@localhost:1521:XE", "java", "vinay0809");
            Connection []connArr = new Connection[7];
       
            for(int i=0; i<connArr.length;i++)
            {
                connArr[i] = cp.checkout();
                System.out.println("Checking out..." + connArr[i]);
                System.out.println("Available Connections ... " + cp.availableCount());
            }                

            for(int i=0; i<connArr.length;i++)
            {
                cp.checkin(connArr[i]);
                System.out.println("Checked in..." + connArr[i]);
                System.out.println("Available Connections ... " + cp.availableCount());
            }
        }
        catch(SQLException sqle)
        {
            sqle.printStackTrace();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }        
    }
}




/**
 * @(#)DBConnect.java
 * @author
 * @version 1.00 2011/5/10
 */

import java.sql.*;

public class DBConnect
{
static Connection con=null;
static final String DBDriver="sun.jdbc.odbc.JdbcOdbcDriver";
static final String DBURL="jdbc:odbc:";
static final String DBName="JAVA";
static final String DBUser="";
static final String DBPassword="";

public Connection getConnection()
{
if(con !=null)
return con;
try
{
con=DriverManager.getConnection("jdbc:odbc:DB2DSN");
}
catch(SQLException e)
{
System.err.println("Cannot connect to database: for DB2. \n Check that DB2 is running and \nthe SKICLUB database Exists.");
}
return con;
}
/**
*main method
*@pram not used
*/
public static void main (String[] args)
{
DBConnect dbdemo=new DBConnect();
System.out.println("Getting Database Driver.");

try
{
Class.forName(DBDriver);
}
catch(ClassNotFoundException e)
{
System.err.println("Cannot load Database Driver:\n for DB2, your classpath muct include\nSQLLIB\\java12\\DB2Java.Zip.");
}
System.out.println("Getting Database Connection");
Connection con=dbdemo.getConnection();
if(con==null)
System.exit(0);
System.out.println("\nDatabase Ready.");
try
{
DatabaseMetaData md=con.getMetaData();
System.out.println("\nProduct Name: "+md.getDatabaseProductName());
System.out.println("\nDriver Name: "+md.getDriverName());
con.close();
}
catch(Exception e)
{
System.err.println(e.getClass().getName()+":"+e.getMessage());
}
}

}