package javahello; import java.sql.*; import java.util.*; public class DBConnectionPool { private String driver; // ドライバクラス private String url; // URL private String user; // ユーザー名 private String password; // パスワード private int maxConnection; // 最大接続数 private int checkedOut; // 貸し出している接続数 private Vector connectionPool = new Vector(); private static DBConnectionPool instance; /** * インスタンスを取得 */ public static synchronized DBConnectionPool getInstance() { if (instance == null) { instance = new DBConnectionPool(); } return instance; } /** * コンストラクタ */ private DBConnectionPool() { this.driver = "org.gjt.mm.mysql.Driver"; this.url = "jdbc:mysql:///hellodb?useUnicode=true&characterEncoding=SJIS"; this.user = ""; this.password = ""; this.maxConnection = 10; } /** * コネクションを取得 */ public synchronized Connection getConnection() throws Exception { Connection con = null; if (connectionPool.size() > 0) { con = (Connection) connectionPool.firstElement(); connectionPool.removeElementAt(0); try { if (con.isClosed()) { con = getConnection(); } } catch (SQLException e) { con = getConnection(); } } else if (maxConnection == 0 || checkedOut < maxConnection) { con = newConnection(); } if (con != null) { checkedOut++; } return con; } /** * 新規にコネクションを作成 */ private Connection newConnection() throws Exception { Class.forName(driver); return DriverManager.getConnection(url, user, password); } /** * コネクションを返却 */ public synchronized void freeConnection(Connection con) { connectionPool.addElement(con); checkedOut--; notifyAll(); } /** * すべてのコネクションを開放 */ public synchronized void release() { Enumeration enumConnections = connectionPool.elements(); while (enumConnections.hasMoreElements()) { Connection con = (Connection)enumConnections.nextElement(); try { con.close(); } catch (SQLException e) { } } connectionPool.removeAllElements(); } }