标签:
String connUrl = "jdbc:mysql://your.database.domain/yourDBname";Class.forName("com.mysql.jdbc.Driver");Connection con = DriverManager.getConnection (connUrl);
String connUrl = "jdbc:mysql://your.database.domain/yourDBname";String driver = "com.mysql.jdbc.Driver";private Map<java.sql.Connection, String> connectionPool = null;private void initPool() {try {connectionPool = new HashMap<java.sql.Connection, String>();Class.forName(driver);for (int poolInd = poolSize; poolInd < 0; poolInd++) {java.sql.Connection con = DriverManager.getConnection(dbUrl);connectionPool.put(con, "AVAILABLE");}}
2、当我们调用connectionProvider.getConnection(),然后它会从集合中获取一个连接,当然状态也会更改为“不可用”。
public java.sql.Connection getConnection() throws ClassNotFoundException, SQLException{boolean isConnectionAvailable = true;for (Entry<java.sql.Connection, String> entry : connectionPool.entrySet()) {synchronized (entry) {if (entry.getValue()=="AVAILABLE") {entry.setValue("NOTAVAILABLE");return (java.sql.Connection) entry.getKey();}isConnectionAvailable = false;}}if (!isConnectionAvailable) {Class.forName(driver);java.sql.Connection con = DriverManager.getConnection(connUrl);connectionPool.put(con, "NOTAVAILABLE");return con;}return null;}
3、当我们关闭得到的连接,ConnectionProvider是不会真正关闭连接。相反,只是将状态更改为“AVAILABLE”。
public void closeConnection(java.sql.Connection connection) throws ClassNotFoundException, SQLException {for (Entry<java.sql.Connection, String> entry : connectionPool.entrySet()) {synchronized (entry) {if (entry.getKey().equals(connection)) {//Getting Back the conncetion to Poolentry.setValue("AVAILABLE");}}}}
标签:
原文地址:http://www.cnblogs.com/liuyongcn/p/4232398.html