Wednesday, August 01, 2012

Concept of Connection Pool using JAVA Code


class MypoolCountMgr
{

 String databaseUrl = "jdbc:oracle://IpAddresss:XXXX/myDatabase";
 String userName = "UN";
 String password = "UP";

 Vector poolCount = new Vector();

 public MypoolCountMgr()
 {
  initialize();
 }

 public MypoolCountMgr(
  String databaseUrl,
  String userName,
  String password
  )
 {
  this.databaseUrl = databaseUrl;
  this.userName = userName;
  this.password = password;
  initialize();
 }

 private void initialize()
 {
  //initialize
  initializepoolCount();
 }

 private void initializepoolCount()
 {
  while(!checkIfpoolCountIsFull())
  {
   System.out.println("Connection is available. We are proceeding to add new connections");
   //Adding new connection
   poolCount.addElement(createNewConnectionForPool());
  }
  System.out.println("Connection Pool is full.");
 }

 private synchronized boolean checkIfpoolCountIsFull()
 {
  final int MAX_POOL_SIZE = 5;

  //Check if the pool size
  if(poolCount.size() < 5)
  {
   return false;
  }

  return true;
 }

 //Normal Code to Creating a new connection
 private Connection createNewConnectionForPool()
 {
  Connection connection = null;

  try
  {
   Class.forName(DRIVER_TOLOAD);
   connection = DriverManager.getConnection(databaseUrl, userName, password);
   System.out.println("Connection: "+connection);
  }
  catch(SQLException sqle)
  {
   System.err.println("SQLException: "+sqle);
   return null;
  }
  catch(ClassNotFoundException cnfe)
  {
   System.err.println("ClassNotFoundException: "+cnfe);
   return null;
  }

  return connection;
 }

 public synchronized Connection getConnectionFromPool()
 {
  Connection connection = null;

  //Check if there is a connection available
  if(poolCount.size() > 0)
  {
   connection = (Connection) poolCount.firstElement();
   poolCount.removeElementAt(0);
  }
    return connection;
 }

 public synchronized void returnConnectionToPool(Connection connection)
 {
  //Adding the connection from the client back to the connection pool
  poolCount.addElement(connection);
 }

 public static void main(String args[])
 {
  MypoolCountMgr MypoolCountMgr = new MypoolCountMgr();
 }

}