예제 #1
0
  /** Returns an unused existing or new connection. */
  public synchronized Connection getConnection() throws Exception {
    if (!initialized) {
      Class c = Class.forName(_driver);
      DriverManager.registerDriver((Driver) c.newInstance());

      initialized = true;
    }

    Connection c = null;
    ConnectionObject co = null;
    boolean badConnection = false;

    for (int i = 0; i < connections.size(); i++) {
      co = (ConnectionObject) connections.elementAt(i);

      // If connection is not in use, test to ensure it's still valid!
      if (!co.inUse) {
        try {
          badConnection = co.connection.isClosed();
          if (!badConnection) badConnection = (co.connection.getWarnings() != null);
        } catch (Exception e) {
          badConnection = true;
          e.printStackTrace();
        }

        // Connection is bad, remove from pool
        if (badConnection) {
          connections.removeElementAt(i);
          trace("ConnectionPoolManager: Remove disconnected DB connection #" + i);
          continue;
        }

        c = co.connection;
        co.inUse = true;

        trace("ConnectionPoolManager: Using existing DB connection #" + (i + 1));
        break;
      }
    }

    if (c == null) {
      c = createConnection();
      co = new ConnectionObject(c, true);
      connections.addElement(co);

      trace("ConnectionPoolManager: Creating new DB connection #" + connections.size());
    }

    return c;
  }
예제 #2
0
  /** Marks a flag in the ConnectionObject to indicate this connection is no longer in use */
  public synchronized void freeConnection(Connection c) {
    if (c == null) return;

    ConnectionObject co = null;

    for (int i = 0; i < connections.size(); i++) {
      co = (ConnectionObject) connections.elementAt(i);
      if (c == co.connection) {
        co.inUse = false;
        break;
      }
    }

    for (int i = 0; i < connections.size(); i++) {
      co = (ConnectionObject) connections.elementAt(i);
      if ((i + 1) > _openConnections && !co.inUse) removeConnection(co.connection);
    }
  }