Augusto Cesar Castoldi wrote:
>
> Ola...
>
> alg�em conhece alguma classe programa que cuida de conexoes com banco de
> dados "ConnectionManager"?
>
> OBS.: Se j� tiver testado no sybase melhor...
>
> at� mais,
>
> Augusto
>
> ------------------------------ LISTA SOUJAVA ----------------------------
> http://www.soujava.org.br - Sociedade de Usu�rios Java da Sucesu-SP
> d�vidas mais comuns: http://www.soujava.org.br/faq.htm
> regras da lista: http://www.soujava.org.br/regras.htm
> historico: http://www.mail-archive.com/java-list%40soujava.org.br
> para sair da lista: envie email para [EMAIL PROTECTED]
> -------------------------------------------------------------------------
import java.sql.*;
import java.util.*;
import java.io.*;
/* Classe para prealoca��o, reutiliza��o e gerenciamento de Conex�es JDBC. */
public class ConnectionPool implements Runnable
{
private String url="url do banco";
private String driver = "driver de conexao";
private String username = "login";
private String password = "senha";
private int maxConnections = 15; //N�mero m�ximo de conex�es caso as
compartilhadas se esgotem
private boolean waitIfBusy = true; //Qdo max de conn for alcan�ado, a pr�xima
requisi��o espera em uma Thread
private Vector ConexoesDisponiveis, ConexoesOcupadas;
private boolean connectionPending = false;
private static ConnectionPool instance;
//Faz com que exista uma �nica inst�ncia da classe ConnectionPool
public static ConnectionPool getInstance()
{
if( instance == null )
{
instance = new ConnectionPool(10); //N�mero de conex�es que s�o compartilhadas
}
return instance;
}
private ConnectionPool(int initialConnections)
{
if (initialConnections > maxConnections)
{
initialConnections = maxConnections;
}
ConexoesDisponiveis = new Vector(initialConnections);
ConexoesOcupadas = new Vector();
try
{
for(int i=0; i<initialConnections; i++) {
ConexoesDisponiveis.addElement(makeNewConnection());
}
}catch(SQLException sql)
{
System.out.println(sql.getMessage());
//Aqui o ideal �,ao inv�s de imprimir o erro, jogar num arquivo de log
}
}
public synchronized Connection getConnection()
{
if (!ConexoesDisponiveis.isEmpty())
{
Connection existingConnection = (Connection)ConexoesDisponiveis.lastElement();
int lastIndex = ConexoesDisponiveis.size() - 1;
ConexoesDisponiveis.removeElementAt(lastIndex);
/** Se a conex�o na lista de conex�es dispon�veis estiver fechada
* (por exemplo por time out), ent�o ela ser� removida da lista
* de conex�es dispon�veis e o processo de se obter uma conex�o
* � repetido. E ainda, as Threads que estiverem dormindo por terem
* atingido o limite maxConnections, ser�o acordadas.
*/
try
{
if (existingConnection.isClosed())
{
notifyAll(); // Freed up a spot for anybody waiting
return(getConnection());
} else
{
ConexoesOcupadas.addElement(existingConnection);
return(existingConnection);
}
}catch(SQLException sql)
{ System.out.println(sql.getMessage());
return null;
}
} else {
/* Tr�s situa��es poss�veis:
1. O limite maxConnections n�o foi atingido. Mas caso n�o haja
uma conex�o dispon�vel, uma nova conex�o � estabelecida
2. O limite maxconnections foi alcan�ado, e a vari�vel waitIfBusy
� false. Ent�o uma SQLException ser� lan�ada
3. O limite maxconnections foi alcan�ado, e a vari�vel waitIfBusy
� true. Ent�o o que acontece � a mesma coisa que a segunda
parte do passo 1: esperar pela proxima conex�o dispon�vel
*/
if ((totalConnections() < maxConnections) && !connectionPending)
{
makeBackgroundConnection();
} else if (!waitIfBusy) {
//throw new SQLException("Connection limit reached");
System.out.println("Limite de conexoes alcancado");
}
/* Espera tanto por uma conex�o a ser estabelecisa, quanto
por uma conex�o liberada
*/
try {
wait();
} catch(InterruptedException ie) {}
// Someone freed up a connection, so try again.
return(getConnection());
}
}
// You can't just make a new connection in the foreground
// when none are available, since this can take several
// seconds with a slow network connection. Instead,
// start a thread that establishes a new connection,
// then wait. You get woken up either when the new connection
// is established or if someone finishes with an existing
// connection.
private void makeBackgroundConnection() {
connectionPending = true;
try {
Thread connectThread = new Thread(this);
connectThread.start();
} catch(OutOfMemoryError oome) {
// Give up on new connection
}
}
public void run() {
try {
Connection connection = makeNewConnection();
synchronized(this) {
ConexoesDisponiveis.addElement(connection);
connectionPending = false;
notifyAll();
}
} catch(Exception e) { // SQLException or OutOfMemory
// Give up on new connection and wait for existing one
// to free up.
}
}
/* Este m�todo explicitamente cria uma nova conex�o.
Sempre chamado em background
*/
private Connection makeNewConnection()
throws SQLException {
try {
// Load database driver if not already loaded
Class.forName(driver);
// Establish network connection to database
Connection connection =
DriverManager.getConnection(url, username, password);
return(connection);
} catch(ClassNotFoundException cnfe) {
// Simplify try/catch blocks of people using this by
// throwing only one exception type.
throw new SQLException("Can't find class for driver: " +
driver);
}
}
public synchronized void free(Connection connection) {
ConexoesOcupadas.removeElement(connection);
ConexoesDisponiveis.addElement(connection);
// Acorda as threads que est�o esperando por uma conex�o
notifyAll();
}
public synchronized int totalConnections() {
return(ConexoesDisponiveis.size() + ConexoesOcupadas.size());
}
/* Fecha todas as conex�o. Mas deve se ter cuidado ao se invocar
este m�todo, pois deve-se garantir que nenhuma conex�o est�
sendo utilizada.
*/
public synchronized void closeAllConnections() {
closeConnections(ConexoesDisponiveis);
ConexoesDisponiveis = new Vector();
closeConnections(ConexoesOcupadas);
ConexoesOcupadas = new Vector();
}
private void closeConnections(Vector connections) {
try {
for(int i=0; i<connections.size(); i++) {
Connection connection =
(Connection)connections.elementAt(i);
if (!connection.isClosed()) {
connection.close();
}
}
} catch(SQLException sqle) {
// Ignore errors; garbage collect anyhow
}
}
public synchronized String toString() {
String info =
"ConnectionPool(" + url + "," + username + ")\n" +
", disponiveis=" + ConexoesDisponiveis.size() + "\n" +
", ocupadas=" + ConexoesOcupadas.size() + "\n" +
", maximo de conexoes=" + maxConnections;
return(info);
}
}
------------------------------ LISTA SOUJAVA ----------------------------
http://www.soujava.org.br - Sociedade de Usu�rios Java da Sucesu-SP
d�vidas mais comuns: http://www.soujava.org.br/faq.htm
regras da lista: http://www.soujava.org.br/regras.htm
historico: http://www.mail-archive.com/java-list%40soujava.org.br
para sair da lista: envie email para [EMAIL PROTECTED]
-------------------------------------------------------------------------