⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 resourcemanager.java

📁 JAVA 经典案例 源代码 Part2.
💻 JAVA
字号:
package org.helpsoft.blog.jdbc;

import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;

public class ResourceManager {
  private static String JDBC_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";

  private static String JDBC_URL = "jdbc:odbc:blog";

  private static String JDBC_USER = "sa";
  private static String JDBC_PASSWORD = "password";

  private static Driver driver = null;

  private static ResourceManager pool;
  private static boolean isDatabaseUp;

  private int minConnections, maxConnections, timeout;


  private LinkedList connections = new LinkedList();


  private LinkedList allConnections = new LinkedList();

  // for sinalizing a release
  private Object releaseSignal = new Object();

  private static final boolean debug = false;

  private ResourceManager() throws SQLException {

    try {
      Class.forName(JDBC_DRIVER);

      this.minConnections = 1;
      this.maxConnections = 100;
      this.timeout = 200;
      if (debug) {
        System.err.println("*********************************************");
        System.err.println("******** 数据库连接池开始 ***********");
        System.err.println("*********************************************");
        System.err.println("driver = " + JDBC_DRIVER);
        System.err.println("minConnections = " + this.minConnections);
        System.err.println("maxConnections = " + this.maxConnections);
        System.err.println("timeout = " + this.timeout);
        System.err.println("*********************************************");
      }

      for (int i = 0; i < this.minConnections; i++) {
        Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USER,
            JDBC_PASSWORD);

        this.connections.addLast(conn);
        this.allConnections.add(conn);

        if (debug) {
          Date now = new Date();
          System.err.println(now.toString() + " openning connection " + (i + 1));
        }
      }

      isDatabaseUp = true;
    }
    catch (ClassNotFoundException e) {
      System.err.println("Ouch... Cannot find database driver: " + JDBC_DRIVER);
    }
  }

  public static void init() throws SQLException {
    if (pool == null || !isDatabaseUp) {
      pool = new ResourceManager();
    }
  }

  public static boolean isDatabaseUp() {
    return isDatabaseUp;
  }

  public static ResourceManager getPool() throws SQLException {
    if (pool == null) {
      init();
    }

    return pool;
  }

  public  synchronized Connection getConnection() throws SQLException {
    Connection conn = null;


    if (this.connections.size() != 0) {
      synchronized (this.connections) {
        conn = (Connection)this.connections.removeFirst();
      }

      // take a look if the connection has died!
      try {
        if (conn.isClosed()) {
          synchronized (this.allConnections) {
            this.allConnections.remove(conn);
            conn = DriverManager.getConnection(JDBC_URL, JDBC_USER,
                                               JDBC_PASSWORD);
            this.allConnections.add(conn);
          }
        }
      }
      catch (SQLException e) {
        if (debug) {
          System.err.println("Cannot reconnect a closed connection:" + e);
        }

        throw e;
      }

      return conn;
    }

    else {
      if (this.allConnections.size() < this.maxConnections) {
        try {
          conn = DriverManager.getConnection(JDBC_URL, JDBC_USER,
                                             JDBC_PASSWORD);
        }
        catch (SQLException e) {
          if (debug) {
            System.err.println(
                "Cannot stabilish a NEW connection to the database:" + e);
          }

          throw e;
        }

        // registering the new connection
        synchronized (this.allConnections) {
          this.allConnections.add(conn);
        }

        return conn;
      }
    }


    System.gc();

    synchronized (this.releaseSignal) {

      if (this.connections.size() == 0) {
        try {
          this.releaseSignal.wait(this.timeout);
        }
        catch (InterruptedException e) {
          if (debug) {
            System.err.println("Problems while waiting for connection. " + e);
          }
        }
      }

      if (this.connections.size() == 0) {
        // TIMED OUT!!!!
        if (debug) {
          System.err.println("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 {
        synchronized (this.connections) {
          conn = (Connection)this.connections.removeFirst();
        }

        return conn;
      }
    }

    return conn;
  }

  public void releaseConnection(Connection conn) throws SQLException {
    if (conn == null) {
      if (debug) {
        System.err.println("Cannot release a NULL connection!");

      }
      return;
    }

    /*
     * Sync because collection.contains() uses the fail fast iterator!
     */
    synchronized (this.allConnections) {
      if (!this.allConnections.contains(conn) && debug) {
        System.err.println(
            "Cannot release a connection that is not from this pool!");

        return;
      }

      try {
        if (conn.isClosed()) {
          this.allConnections.remove(conn);

          return;
        }
      }
      catch (SQLException e) {
        if (debug) {
          System.err.println("Cannot get info about the conn: " + e);
        }
      }
    }

    synchronized (this.releaseSignal) {
      synchronized (this.connections) {
        this.connections.addLast(conn);
      }

      this.releaseSignal.notify();
    }

    if (debug) {
      System.err.println("Releasing connection...");
    }
  }

  public synchronized String getStatus() {
    StringBuffer status = new StringBuffer();
    int i = 0;

    Iterator it = this.allConnections.iterator();
    while (it.hasNext()) {
      i++;
      status.append("Connection " + i + ": ");

      Connection c = (Connection) it.next();
      if (c != null) {
        try {
          status.append(c + " closed: " + c.isClosed());
        }
        catch (SQLException e) {
          status.append(e);
        }
      }
      else {
        status.append("NULL!!!");
      }

      status.append("\n");
    }

    status.append("\nPOOL:\n\n");
    i = 0;

    it = this.connections.iterator();
    while (it.hasNext()) {
      i++;
      status.append("Connection " + i + ": ");

      Connection c = (Connection) it.next();
      if (c != null) {
        try {
          status.append(c + " closed: " + c.isClosed());
        }
        catch (SQLException e) {
          status.append(e);
        }
      }
      else {
        status.append("NULL!!!");

      }
      status.append("\n");
    }

    return status.toString();
  }

  /**
   * Pega o total de registors retornados por uma instrucao SELECT.
   *
   * @param rs Referencia para um objeto <code>ResultSet</code> que contem o sql executado
   * @return Numero total de registros
   * @throws Exception
   * */
  public static int getRowCount(ResultSet rs) throws SQLException {
    int total = 0;

    rs.last();
    total = rs.getRow();
    rs.beforeFirst();

    return total;
  }




  public static void close(Connection conn) {
    try {
      if (conn != null) {
        conn.close();
      }
    }
    catch (SQLException sqle) {
      sqle.printStackTrace();
    }
  }

  public static void close(PreparedStatement stmt) {
    try {
      if (stmt != null) {
        stmt.close();
      }
    }
    catch (SQLException sqle) {
      sqle.printStackTrace();
    }
  }

  public static void close(ResultSet rs) {
    try {
      if (rs != null) {
        rs.close();
      }
    }
    catch (SQLException sqle) {
      sqle.printStackTrace();
    }

  }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -