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

本文介绍了一个简单的数据库连接池实现方案,使用Java语言并通过LinkedList管理连接。该连接池能够初始化一定数量的连接,并支持获取和释放连接操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值