import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.util.Calendar;
import java.util.HashMap;
//@author 黄本华
//@version 1.0 2005-12
//@deprecated 这是一个连接池的管理程序
//解决关闭无法统一的问题
public final class ConnectionPool {
 private static Connection createConnection(){
  //TODO 返回JDBC连接
  return null;
 }
 //调用的方法
 public final Connection getConnection(){
  if(pool.isEmpty())return new ProxyConnection(this).getConnection();
  long time = -1;
  Integer idx = 0;
  for(Integer i: pool.keySet()){
   ProxyConnection proxy = pool.get(i);
   if(proxy.time < 1)return proxy.getConnection();
   if(time < 0){
    time = proxy.time;
    idx = i;
   }else if(time < proxy.time){
    time = proxy.time;
    idx = i;
   }
  }
  //20个就认为快满了
  if(pool.size() < 20)return new ProxyConnection(this).getConnection();
  //10 分钟失效
  if(time() - time < 600000)return new ProxyConnection(this).getConnection();
  return pool.get(idx).getConnection();
 }
 
//////////////////////////////
//连接池
private HashMap<Integer, ProxyConnection> pool = new HashMap<Integer, ProxyConnection>();
//连接代理
public final class ProxyConnection implements InvocationHandler{
 private int id=0;
 private ConnectionPool pool;
 private Connection proxy, connection;
 private long time = 0;
 //初始化
 private ProxyConnection(ConnectionPool pool){  
  this.pool = pool;
  id = this.pool.getId();
  connection = createConnection();
  if(connection == null)return;
  try{
   proxy = (Connection)Proxy.newProxyInstance(
    connection.getClass().getClassLoader(),
    connection.getClass().getInterfaces(),
    this);
  }catch(Exception e){
   try{connection.close();
   }catch(Exception ee){ }
   return;
  }
  this.pool.add(this);
 }
 //获取连接
 public Connection getConnection(){
  time = time();
  return proxy;
 }
 //截获
 public Object invoke(Object o, Method m, Object[] args) throws Throwable {  
  if("close".equals(m.getName())){
   time = 0;
   return null;
  }
  time = time();
  return m.invoke(connection, args);  
 }
}
//取当前时间
private static long time(){
 return Calendar.getInstance().getTimeInMillis();
}
//获取一个ID标示
private int max = 0;
private synchronized int getId(){
 return ++ max;
}
//向连接池添加一个连接
private synchronized void add(ProxyConnection proxy){
 pool.put(proxy.id, proxy);
}
}