模拟一个ConnectionDriver,用于创建Connection

package tread.demo.threadpool;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.util.concurrent.TimeUnit; public class ConnectionDriver {
static class ConnectionHandler implements InvocationHandler { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return null;
}
} public static final Connection createConnection() {
return (Connection) Proxy.newProxyInstance(ConnectionDriver.class.getClassLoader(), new Class<?>[]{Connection.class}, new ConnectionHandler());
}
}

线程池的实现:

package tread.demo.threadpool;

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.createConnection());
}
}
} public void releaseConnection(Connection connection) {
if (connection != null) {
synchronized (pool) {
pool.addLast(connection);//将Connection还回给Pool
pool.notifyAll();//通知等待的线程
}
}
} public Connection fetchConnection(long mills) throws Exception {
synchronized (pool) {
if (mills <= 0) {
while (pool.isEmpty()) {
pool.wait();//一直等带release-》Notify
}
return pool.removeFirst();//得到一个connection
} else {
long future = System.currentTimeMillis() + mills;
long remaining = mills;
while (pool.isEmpty() && remaining > 0) {//基于时间进行等待,一直到超时。
pool.wait();
remaining = future - System.currentTimeMillis();
}
Connection result = null;
if (!pool.isEmpty()) {
result = pool.removeFirst();
}
return result;
}
}
}
}

两点:

  1. 对象的wait和notify
  2. 基于超时时间的等待。

测试:


package tread.demo.threadpool;

import java.sql.Connection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger; public class ConnectionPoolTest {
static ConnectionPool pool = new ConnectionPool(10);
static CountDownLatch start = new CountDownLatch(1);
static CountDownLatch end; public static void main(String[] args) throws Exception {
int threadCount = 1000;
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), "ConnectionRunnerThread");
thread.start();
}
start.countDown();//tart的CountDown为0,保证了所有线程同时执行。
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;
} public void run() {
try {
start.await();//等待start的CountDown为0.
} catch (InterruptedException e) {
e.printStackTrace();
}
while (count > 0) {
try {
Connection connection = pool.fetchConnection(1);//超时时间
if (connection != null) {
try {
connection.createStatement();
} finally {
pool.releaseConnection(connection);
got.incrementAndGet();
}
} else {
notGot.incrementAndGet();
}
} catch (Exception ex) {
} finally {
count--;
}
}
end.countDown();
}
}
}

继续巧用了CatdownLatch

结果:

total invoke: 20000
got connection: 11914
not got connection: 8086

如果调整超时时间,调整为100ms

结果如下(大部分时候都能得到connection)

total invoke: 20000
got connection: 19050
not got connection: 950

用java多线程模拟数据库连接池的更多相关文章

  1. java多线程模拟生产者消费者问题,公司面试常常问的题。。。

    package com.cn.test3; //java多线程模拟生产者消费者问题 //ProducerConsumer是主类,Producer生产者,Consumer消费者,Product产品 // ...

  2. Java多线程与线程池技术

    一.序言 Java多线程编程线程池被广泛使用,甚至成为了标配. 线程池本质是池化技术的应用,和连接池类似,创建连接与关闭连接属于耗时操作,创建线程与销毁线程也属于重操作,为了提高效率,先提前创建好一批 ...

  3. Java 多线程:线程池

    Java 多线程:线程池 作者:Grey 原文地址: 博客园:Java 多线程:线程池 CSDN:Java 多线程:线程池 工作原理 线程池内部是通过队列结合线程实现的,当我们利用线程池执行任务时: ...

  4. Java自学-JDBC 数据库连接池

    数据库连接池 与线程池类似的,数据库也有一个数据库连接池. 不过他们的实现思路是不一样的. 本章节讲解了自定义数据库连接池类:ConnectionPool,虽然不是很完善和健壮,但是足以帮助大家理解C ...

  5. java 多线程 4 线程池

    系统启动一个新线程的成本是比较高的,因为它涉及到与操作系统的交互.在这种情况下,使用线程池可以很好的提供性能,尤其是当程序中需要创建大量生存期很短暂的线程时,更应该考虑使用线程池. 与数据库连接池类似 ...

  6. java多线程:线程池原理、阻塞队列

    一.线程池定义和使用 jdk 1.5 之后就引入了线程池. 1.1 定义 从上面的空间切换看得出来,线程是稀缺资源,它的创建与销毁是一个相对偏重且耗资源的操作,而Java线程依赖于内核线程,创建线程需 ...

  7. Java 多线程之线程池的使用

    一. 使用背景 谈到Java多线程,我们很自然的会想到并发,在编写多线程代码时,我们一般会创建多个线程,如果并发的线程数量很多,而且每个线程都是执行一个时间很短的任务就结束了,这样频繁的进行线程的创建 ...

  8. Java多线程:线程池

    一. 背景 线程是稀缺资源,如果无限制的创建,不仅会消耗系统资源,还会降低系统的稳定性,合理的使用线程池可以对线程进行统一的分配.调优和监控,并有以下好处:     第一:降低资源消耗.通过重复利用已 ...

  9. java多线程、线程池及Spring配置线程池详解

    1.java中为什么要使用多线程使用多线程,可以把一些大任务分解成多个小任务来执行,多个小任务之间互不影像,同时进行,这样,充分利用了cpu资源.2.java中简单的实现多线程的方式 继承Thread ...

随机推荐

  1. [BJOI2019]光线(DP)

    降智了…… 当你走头无路的时候就应该知道瞎搞一个DP: $p[i]$ 表示光射入第 $1$ 块玻璃时,从第 $i$ 块玻璃出去的光量. $q[i]$ 表示光射入第 $i$ 块玻璃时,从第 $i$ 块玻 ...

  2. 图论问题(2) : hdu 1102

    题目转自hdu 1102,题目传送门 题目大意: 输入一个n*n的邻接矩阵,其中i行j列代表从i到j的路径的长度 然后又m条路已经帮你修好了,求最短要修多长的路才能使所有村庄连接 不难看出,这道题就是 ...

  3. Sentinel: 分布式系统的流量防卫兵

    前言 在 Spring Cloud 体系中,熔断降级我们会使用 Hystrix 框架,限流通常会在 Zuul 中进行处理,Zuul 中没有自带限流的功能,我们可以自己做限流或者集成第三方开源的限流框架 ...

  4. VIPKID:笔试题(数组中和为0的一对数的数量,十进制转二进制中1的个数)

    1. 求数组中的和为0 的一对数的数量 注意,需要用到set import java.util.Scanner; public class Main{ public static void main( ...

  5. ECMAScript 初探 - 对象篇

    一.对象 如果你用过 C++ 或 Java,肯定熟悉类(class).在 ECMAScript 中并没有 "类" 这个词, 其对应的是 "对象定义",不过这太拗 ...

  6. navicat for Mysql查询数据不能直接修改

    navicat for Mysql查询数据不能直接修改 原来的sql语句: <pre> select id,name,title from table where id = 5;</ ...

  7. linux vsftp查看ftp账号信息的方法

    linux vsftp查看ftp账号信息的方法 查看注册的FTP账号 在/etc/vsftpd/chroot_list 密码看不到 只能重置密码 passwd username

  8. CentOS7安装图形化界面方法

    一.linux安装(root用户操作) 1. 安装vncserver; yum install tigervnc-server 2. 安装vncviewer; yum install vnc 3. 设 ...

  9. ubutun16.04 安装编译glog日志库

    glog 是一个 C++ 日志库,它提供 C++ 流式风格的 API.在安装 glog 之前需要先安装 gflags,这样 glog 就可以使用 gflags 去解析命令行参数(可以参见gflags ...

  10. 使用AtomicInteger写一个显示锁

    利用了AtomicInteger的compareAndSet方法 public class CASLock { private AtomicInteger value = new AtomicInte ...