Fiz um pool SIMPLERRIMO, e os dois metodos principais sao o getConnection e o releaseConnection.
Fiz testes concorrentes, com 3 threads de 800 queries cada. Mas voce sabe como eh, teste de concorrencia pode passar batido, e um dia da pau. Alguem me ajuda a achar algo?
Pra deixar claro, releaseSignal eh apenas um mutexiznho. connections guarda as conexoes do pool atual, e allConections guarda todas, as usadas e nao usadas.
/**
* Gets a connection to the database.<p>
* So you need to release it, after use. If you are using a <code>Query</code>,
* its finalize method will release it. It will not be a huge problem if you do not
* release it, but this way you will get a better performance.<p>
* Thread safe.
*/
public synchronized Connection getConnection() throws DAOException {
Connection conn = null;
// if there is enought Connections
if (connections.size() != 0) {
conn = (Connection) connections.removeFirst();
return conn;
}
// Otherwise, create a new one if the Pool is now full
else {
if (allConnections.size() < this.maxConnections) {
try {
conn = DriverManager.getConnection(connectionString);
}
catch (SQLException e) {
throw new DAOException("Cannot stabilish a NEW connection to the database.", e);
}
// registering the new connection
allConnections.add(conn);
return conn;
}
}
/*
* Trying to get some Connections stuck inside some Queries.
* The Query.finalize method will release them.
* We need to wait sometime, so the GC will get the Connections for us
*/
System.gc();
synchronized (releaseSignal) {
/*
* Not inside a while, since we are giving it a maximum timeout,
* and this method is already SYNC, there is no way that we will loose
* the state if we receive a signal
*/
if (connections.size() == 0) {
try {
releaseSignal.wait(timeout);
}
catch (InterruptedException e) {
throw new DAOException("Problems while waiting for connection", e);
}
}
if (connections.size() == 0) {
// TIMED OUT!!!!
throw new DAOException(
"Pool is empty, and th waiting for one timed out!"
+ "If this is happening too much, your code is probably not releasing the Connections."
+ "If you cant solve this, set your 'database.connection.pool.timeout' to a bigger number.");
}
else {
return (Connection) connections.removeFirst();
}
}
}
/**
* Releases a connection, making it available to the pool once more.
*/
public void releaseConnection(Connection conn) throws DAOException {
synchronized (releaseSignal) {
connections.addLast(conn);
releaseSignal.notify();
}
}