java连接池透过动态代理和线程通讯实现

java连接池通过动态代理和线程通讯实现
1.代理类

package com.cgm.threadpool;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;

public class ConUtils1 {

private static List<Connection> pool=new ArrayList<Connection>();
static{
try {

Class.forName("oracle.jdbc.driver.OracleDriver");
String url="jdbc:oracle:thin:@127.0.0.1:1521:ORCL";

String user="scott";
String passWord="tiger";
for (int i = 0; i < 3; i++) {
final Connection conn=  DriverManager.getConnection(url, user, passWord);

//产生被代理对象对conn进行代理
Object  connObj=Proxy.newProxyInstance(
ConUtils1.class.getClassLoader(),
new Class[]{Connection.class},
new InvocationHandler() {

public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if (method.getName().equals("close")) {
System.out.println("不能关啊,还要链接");
}else{
System.out.println(method.getName());
return method.invoke(conn, args);
}


synchronized (pool) {
//这个peoxy就是    connObj
pool.add((Connection) proxy);
//加进去了就放行
pool.notify();



}

return null;
}
});


pool.add((Connection) connObj); //加被代理对象能拦截啊,只能拦截代理对象
}
} catch (Exception e) {
throw  new RuntimeException();
}
}

/*
* 提供一个静态工厂方法 返回一个链接
*/
public static  Connection getCon(){
  synchronized (pool) {
 
  if (pool.size()==0) {  //发现没有----等待
try {
//Thread.sleep(1000);
pool.wait();  //没有就等待
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return  getCon();  //递归 直到拿到为止
}
 
 
  Connection conn=pool.remove(0); //返回一个代理的Connection类
return  conn;
}
}
}







2.thread类
package com.cgm.threadpool;

import java.sql.Connection;
import java.sql.Statement;

public class MyThread extends  Thread{

@Override
public void run() {
Connection conn=null;

try {
conn=ConUtils1.getCon();  //取得链接
System.err.println(this.getName()+","+conn);
conn.setAutoCommit(false);//设置失去的开始
String sql=" insert into userss values('"+this.getName()+"','Tom','49')";
Statement st=conn.createStatement();
st.execute(sql);
conn.commit();

  //
//new MyThread().start();
//Thread.sleep(100);

System.out.println(this.getName()+"子线程执行完成");
// Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}finally{

try {
conn.setAutoCommit(true);
conn.close();   //close变成了还链接
// ConUtils.back(conn);  //还连接
} catch (Exception e2) {
e2.printStackTrace();
}

}




}
   
}









3.测试类


package com.cgm.threadpool;

import java.sql.Connection;
import java.sql.Statement;

public class ThreadDemo  {
public static void main(String[] args) throws Exception {
for (int i = 0; i < 30; i++) {
new MyThread().start();
}

}
}