1.概述

频繁的创建和销毁数据库连接消耗非常多的系统资源,创建一个池子, 管理一定数量的连接,用的时候去池中取,用完了放回池中,这时比较通用的做法。

2.关键字

LinkedList  synchronized  InvocationHandler  CountDownLatch

3. 代码

3.1 ConnectionPool.java

package com.rocky.pool;

import java.sql.Connection;
import java.util.LinkedList; public class ConnectionPool { private LinkedList<Connection> pool = new LinkedList<Connection>(); public ConnectionPool(int initialSize){
if(initialSize > 0){
for(int i=0; i<initialSize; i++){
pool.addLast(ConnectionDriver.createConection());
}
}
} public void releaseConnection(Connection connection){
if(connection != null){
synchronized (pool) {
//连接释放后 要进行通知 这样其他消费者能够感知池中已经归还了一个连接
pool.addLast(connection);
// pool.notifyAll();//all
pool.notify();//all }
}
} public Connection fetchConnection(long mills) throws InterruptedException{
synchronized (pool) {
//超时
if(mills <= 0){
while(pool.isEmpty()){
pool.wait();
}
return pool.removeFirst();
}else{
long future = System.currentTimeMillis() + mills;
long remaining = mills;
while(pool.isEmpty() && remaining >0){
pool.wait(remaining);
remaining = future - System.currentTimeMillis();
}
Connection result = null;
if(!pool.isEmpty()){
result = pool.removeFirst();
}
return result;
}
} }
}

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语言)的更多相关文章

  1. 数据源与JNDI资源实现JSP数据库连接池实例

    名词解释:JNDI的全称是java命名与目录接口(Java Naming and Directory Interface),是一个应用程序设计的API,为开发人员提供了查找和访问各种命名和目录服务的通 ...

  2. [数据库连接池二]Java数据库连接池--C3P0和JDNI.

    前言:上一篇文章中讲了DBCP的用法以及实现原理, 这一篇再来说下C3P0和JDNI的用法. 1.1.C3P0数据源 C3P0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规 ...

  3. mongodb数据库连接池(java版)

    mongodb数据库接口的设计 package storm.db; import java.util.ArrayList; import com.mongodb.DB; import com.mong ...

  4. 简单理解数据库连接池(JDBC)

    为什么要使用连接池? 在我们写代码的时候,写了很多类,假如这些类都和数据库打交道.这样的话每个类都要去获取数据库连接,操作完了之后就把连接释放了. 要知道,获取数据库连接的操作其实是向操作系统底层去获 ...

  5. Python数据库连接池实例——PooledDB

    不用连接池的MySQL连接方法 import MySQLdbconn= MySQLdb.connect(host='localhost',user='root',passwd='pwd',db='my ...

  6. Python数据库连接池实例——PooledDB

    不用连接池的MySQL连接方法 import MySQLdb conn= MySQLdb.connect(host='localhost',user='root',passwd='pwd',db='m ...

  7. dbcp数据库连接池的java实现

    1.准备 导入jar包 commons-dbcp-1.4.jar commons-pool-1.3.jar 数据库驱动包,如:mysql-connector-java-5.1.28-bin.jar 2 ...

  8. C3P0数据库连接池的java实现

    1.配置准备 导入jar包 c3p0-0.9.2-pre1.jar mchange-commons-0.2.jar 数据库驱动包,如:mysql-connector-java-5.1.28-bin.j ...

  9. 第77节:Java中的事务和数据库连接池和DBUtiles

    第77节:Java中的事务和数据库连接池和DBUtiles 前言 看哭你,字数:8803,承蒙关照,谢谢朋友点赞! 事务 Transaction事务,什么是事务,事务是包含一组操作,这组操作里面包含许 ...

随机推荐

  1. JavaScript中setInterval的用法总结

    setInterval动作的作用是在播放动画的时,每隔一定时间就调用函数,方法或对象.可以使用本动作更新来自数据库的变量或更新时间显示. setInterval动作的语法格式如下:setInterva ...

  2. php获取随机字符串的几种方法

    方法一:shuffle函数(打乱数组)和mt_rand函数(生成随机数,比rand速度快四倍) /** * 获得随机字符串 * @param $len 需要的长度 * @param $special ...

  3. 23.each和map函数

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  4. C#获取当前程序集的完整路径

    //获取当前程序集的完整路径加上EXE的名称 string binPath = Assembly.GetExecutingAssembly().Location; Console.WriteLine( ...

  5. 51 Nod 1042 数位dp

    1042 数字0-9的数量 1 秒 131,072 KB 10 分 2 级题   给出一段区间a-b,统计这个区间内0-9出现的次数. 比如 10-19,1出现11次(10,11,12,13,14,1 ...

  6. six

    团队序号:6组 团队名称:拯救地球小分队 团队项目的码云地址:https://gitee.com/lwj5950/seflash 此次博客撰写人姓名:刘威骏 学号:2017*****7168 团队中的 ...

  7. @RequestMapping的value属性

    package com.zby.controller; import javax.servlet.http.HttpServletRequest; import org.springframework ...

  8. 微信 vue中使用video.js播放m3u8视频,解决安卓自动全屏的问题。

    最近一个项目中需要在微信中播放m3u8格式的视频,刚开始用了 vue-video-player 这个插件,在IOS手机体验良好,本以为完事了, 结果安卓手机一点播放就自动全屏,心态略崩.查了资料说是安 ...

  9. spring框架中的aop技术

    1. 什么是AOP, 面向切面编程 AOP为Aspect Oriented Programming的缩写, 意为:面向切面编程,主要是使各部分之间的耦合度降低, 提高程序的可重用性, 同时提高了开发的 ...

  10. vue-webpack项目中调试的问题

    在使用devtools的过程中,可以使用debugger.