Introduction
In this post, I try to make something like a connection pool mechanism in generic workflow project. In my company, the code is used to solve max cursor exceed
in connection as work flow engine is multithreaded and manages many requests at the time may use database.
Background
I used my work experience to make my connection pool in Java programming.
Using the Code
This block of Java code gets connection free to use in other subsystems:
Connection GetConnection(DBNames name) {
Connection conn = null;
int j = -1;
for(Map.Entry<Connection,Integer>entity :pooledconn.entrySet()) {
if(entity.getValue()<max) {
j = entity.getValue();
synchronized(this)
{
pooledconn.put(entity.getKey(),++j);
}
conn = entity.getKey();
break;
}
}
if(j==-1) {
this.SelectDB(name);
conn = this.GetConnection(name);
}
if(conn==null) {
System.out.println("Exceeded"+ this.max+"\n");
this.max++;
if(this.max<Max_conn){
conn = this.GetConnection(name);
this.max++;
}
else {
System.out.print("Sleeping To gain connection");
long EndTime = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while(this.max>Max_conn) {
try {
Thread.sleep(2000);
if(System.nanoTime()>EndTime) {
break;
}
System.out.println("Critical Load");
} catch (InterruptedException e) {
}
conn = this.GetConnection(name);
this.max++;
}
}
}
return conn;
}
If anyone here can improve this code and share your experience, you are welcome.