时间:2021-07-01 10:21:17 帮助过:42人阅读
3.2 ConnectionDriver.java
package com.rocky.pool; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.Connection; public class ConnectionDriver { static class ConnectionHandler implements InvocationHandler{ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if(method.getName().equals("commit")){ Thread.sleep(1000); } return null; } } //创建一个connection的代理 public static Connection createConection(){ return (Connection) Proxy.newProxyInstance(ConnectionDriver.class.getClassLoader(), new Class<?>[]{Connection.class},new ConnectionHandler()); } }
3.3 ConnectionPoolTest.java
package com.rocky.pool; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; public class ConnectionPoolTest { static ConnectionPool pool = new ConnectionPool(10); //保证所有runner能够同时运行 static CountDownLatch start = new CountDownLatch(1); static CountDownLatch end ; public static void main(String[] args) throws Exception { int threadCount = 20; end = new CountDownLatch(threadCount); int count = 20; AtomicInteger got = new AtomicInteger(); AtomicInteger notGot = new AtomicInteger(); for(int i=0; i<threadCount; i++){ Thread thread = new Thread(new ConnectionRunner(count, got, notGot), "ConectionRunnerThread"+i); thread.start(); } start.countDown(); end.await(); System.out.println("total invoke: "+ (threadCount) * count); System.out.println("got connection: "+got); System.out.println("not got connection "+ notGot); } static class ConnectionRunner implements Runnable{ int count ; AtomicInteger got; AtomicInteger notGot; public ConnectionRunner(int count, AtomicInteger got, AtomicInteger notGot){ this.count = count; this.got = got; this.notGot = notGot; } @Override public void run() { try { start.await(); } catch (InterruptedException e) { e.printStackTrace(); } while(count > 0){ try { Connection connection = pool.fetchConnection(1000); if(connection != null){ try{ connection.createStatement(); connection.commit(); }finally{ pool.releaseConnection(connection); got.incrementAndGet(); } }else{ notGot.incrementAndGet(); } } catch (InterruptedException | SQLException e) { e.printStackTrace(); }finally{ count--; } } end.countDown(); } } }
3.4 说明
通过改变main方法中的threadCount的数量可以观察 随着线程数的增加 获取连接命中的比例在下降,
这时因为连接池中的连接数一定(10个) 而客户端线程会等待并超时返回。
简单的数据库连接池实例(java语言)
标签:感知 lex -- load exce 超时 handler etc stack