java 数据库 一道题

来源:百度知道 编辑:UC知道 时间:2024/06/25 05:31:19
当我们连database 先建立 connection,然后 再关闭connection;
但是这种写法 在大型的数据库应用中效率就常低. 我最常用的datasource(连接池) 典型的像weblogic上的连接池.
连接池原理很复杂(百度一下,这儿不说),简单的讲就是 建立一定的连接数在数据库 server 上. 当客户要用时 。直接拿,不用了在还回来.
请大家实现这个简单的 连接池功能。要考虑单线程问题。 因为客户单用可能
不停的点查询。50分
yaoweijq 你那 getConnetion 是有问题的。当相同客户端不断发出连接请求时.连接池很快会耗尽.
你的因为,判断连接池为时则new Connection 所有看不出来.

package com.yaowei.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Vector;
public class connectionPool implements connectionPoolInterface{
private static Vector<Connection> pool;
private final int POOL_MAX_SIZE = 50;
private static connectionPool conPool = null;
private connectionPool(){

}
public static connectionPool getInstance(){
if(conPool == null)
return new connectionPool();
else
return conPool;
}
public synchronized Connection getConnection() {
Connection con = null;
try{
if(pool == null)
pool = new Vector<Connection>();
if(pool.isEmpty()){
con = this.createConnection();
}else
{
int index = pool.size() - 1;
con = pool.get(index);
pool.remove(pool.get(index));
}
}catch(Exception e){
e.printStackTrace();
}