Language Translator

Java Code for Connection Pooling / Connection Pooling in Java

public class MyConnection {

private boolean inUse ;

public MyConnection() {
this.inUse = false;
}

public void setInUse()
{
this.inUse = true;
}

public void setNotInUse()
{
this.inUse = false;
}


public boolean isInUse() {
return inUse;
}

}


import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;

public class MyconnectionPool
{

private static HashSet connSet;
private static final int defaultSize = 10;
private int maxPoolSize = 10;
private static MyconnectionPool myconnectionPool;

static
{

connSet = (HashSet) Collections
.synchronizedSet(new HashSet(defaultSize));

int connCounter = 0;

while (connCounter < defaultSize)
{
connSet.add(new MyConnection());
}

}

public static MyconnectionPool getInstance()
{

if (myconnectionPool == null)
{
myconnectionPool = new MyconnectionPool();
}

return myconnectionPool;
}

public MyConnection acquireConnection() throws Exception
{

if (connSet != null)
{
if (connSet.isEmpty())
{
throw new Exception("Connection Pool is empty");
}
else
{
synchronized (connSet)
{

Iterator connIterator = connSet.iterator();

MyConnection myConn = null;

while (connIterator.hasNext())
{
myConn = connIterator.next();

if (myConn.isInUse())
{
continue;
}
else
{
return myConn;
}
}

if (connSet.size() < maxPoolSize)
{
myConn = new MyConnection();

myConn.setInUse();

connSet.add(myConn);

return myConn;
}
else
{
throw new Exception("Connection Pool is full ");
}

}

}
}
else
{
throw new Exception("Connection Pool is not initialised");
}
}
}

No comments:

Post a Comment