对象池的

对象池是存放一组特定的对象的容器。对象池是解决性能的一种途径,当我们使用一个对象比较频繁的时候,而且该对象不某些属性不是公有的,就需要通过创建对象池将它们存放起来,避免频繁的创建销毁的开销。

 

 

下面是数据库连接池的实现原理:

 

 

/**
 * 数据库连接池
 * 
 * @author Administrator
 * 
 */
public class DBConnectionPool {

	private final static int MAX_SIZE = 10;
	private final static int MIN_SIZE = 3;

	private final static Vector pool = new Vector();

	static {
		for (int i = 0; i < MIN_SIZE; i++) {

			pool.add(createConnection());
		}
	}

	/**
	 * 得到一个数据库的连接,如果当前池里面没有连接,创建一个新的连接,如果数据库连接池里面有 连接,那么从池里面得到
	 * 
	 * @return
	 */
	public static synchronized Connection getConnection() {

		System.out.println(pool.size());
		Connection conn = null;
		if (pool.isEmpty()) {
			conn = createConnection();

		} else {
			int index = pool.size() - 1;
			conn = (Connection) pool.get(index );
			pool.remove(conn);
		}

		return conn;
	}

	 
	private static Connection createConnection() {
		Connection conn = null;
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection(
					"jdbc:oracle:thin:@127.0.0.1:1521:ysen", "ysen", "123");

		} catch (ClassNotFoundException e) {
			 			e.printStackTrace();
		} catch (SQLException e) {
			 			e.printStackTrace();
		}

		return conn;
	}

	 
	public static synchronized void close(Connection conn) {
		if (pool.size() >= MAX_SIZE) {
			try {
				conn.close();
			} catch (SQLException e) {
								e.printStackTrace();
			}
		} else if (pool.size() < MAX_SIZE) {
			pool.add(conn);
		}

	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值