Friday, July 9, 2010

My own ConnectionPool implementation

By seeing this example we can get the two things

1- how to implement our own connection
2-why sun gives wait , notify methods in object class.

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Vector;
public class MyConnectionPool {
Vector connections= null;
static MyConnectionPool instance=null;
public static final int MAX_CONNECTIONS=10;

//removeAllConnections objects
public synchronized void removeAllConnections() {
if (connections==null) {
return;
}
try {
int sz= connections.size();
for (int i=0; i < sz/2; i++) {
Connection c= (Connection) connections.elementAt(i);
c= null;
connections.remove(i);
}
if (connections!= null && connections.size() > 0) {
connections.removeAllElements();
}
connections= null;
}catch (Exception e) {
System.out.println( "Error "+ e);
}
instance =null;
}

//getInstance...
public static MyConnectionPool getInstance() {
if (instance ==null)
instance= new MyConnectionPool();
return instance;
}

//initializing all connections upto max limit i.e upto 10 connections...
public synchronized void initialize() {
if (connections ==null) {
try {
Class.forName(" com.mysql.jdbc.Driver ");
connections= new Vector();
int count =0;
while (count < MAX_CONNECTIONS) {
Connection connection=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger");
connections.addElement(connection);
count++;
}
System.out.println( "total connections created r:" + count);
} catch (Exception e) {
System.out.println( "initialise:Exception ");
e.printStackTrace();
instance.removeAllConnections();
initialize();
}
}
}
//getting connection....
public synchronized Connection getConnection() {
System.out.println( "getConnection ");
Connection c =null;
System.out.println("connections"+connections.size());
if (connections== null)
return null;
if (connections.size() > 0) {
System.out.println("i am in if");
c =(Connection) connections.elementAt(0);
connections.removeElementAt(0);
}else
{
System.out.println("i am in else");
try {
wait();
c =(Connection) connections.elementAt(0);
connections.removeElementAt(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return c;
}
//put connection obj into vector.
public synchronized void putConnection(Connection c) {
if (c != null) {
connections.addElement(c);
notifyAll();
}
}
}

3 comments:

Anonymous said...

Hmm, this pool was never used in practice right?
There is no close() method.
How do you ensure that after having closed a connection the client does not continue to use the connection he once retrieved?

Andi

Javin Paul said...

Nice post , thanks for sharing information.

Javin
How HashMap works in Java

Gan said...

I can't able to add me as your followers..

Post a Comment