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]
-------------------------------------------------------------------------

Responder a