36.自己写的一个开源连接池功能

public class ConnectionPool {
	private LinkedList<Connection> pool;
	private static String url = "jdbc:mysql://w.rdc.sae.sina.com.cn:3307/app_imu2b";
	private static String saeAccessKey = null;
	private static String saeSecretKey = null;
	private static int maxCount = 200;
	private static int currentCount = 50; // 因为初始的就是50个
	public ConnectionPool() {
		pool = new LinkedList<Connection>();
		saeAccessKey = SaeUserInfo.getAccessKey();
		saeSecretKey = SaeUserInfo.getSecretKey();
		for (int i = 0; i < 50; i++) {
			try {
				Connection conn;
				conn = DriverManager.getConnection(url, saeAccessKey,
						saeSecretKey);
				pool.addLast(conn);
			} catch (SQLException e) {
				throw new InitializeErrorException(e.getMessage());
			}

		}

	}
	public Connection getConnection() {
		synchronized (ConnectionPool.class) {
			Connection conn = null;
			if (pool.size() > 0)
				return pool.removeFirst();
			else if (currentCount < maxCount) {
				try {
					conn = DriverManager.getConnection(url, saeAccessKey,
							saeSecretKey);
					currentCount++;
					pool.addLast(conn);
				} catch (SQLException e) {

				}
				return pool.removeFirst();
			} else {
				throw new ExceptionInInitializerError("SQL连接已经是最大值");
			}

		}

	}
	public void free(Connection conn) {
		pool.addFirst(conn);
	}
}

你可能感兴趣的:(java,数据库,jdbc,LinkedList)