并发实战(1)- 模拟等待超时模式的连接池

并发实战(1)- 模拟等待超时模式的连接池

前言

我们来进行并发的实战,用等待超时模式来实现连接池的功能。
不管是在Spring还是Mybatis中的的连接池,都是按照等待超时的思想来实现的。
接下来简单的来实现一个等待超时模式的连接池

什么是等待超时模式的连接池

什么是等待超时模式的连接池,从名字中可以看到就是通过等待与等待超时来实现一个连接池。连接池也就是一个池子容器,里面放着我们定义好的连接,在需要的时候从中取出连接,并且在使用完成后归还接连,减少了连接创建与销毁的性能消耗。
所以我们想实现一个等待超时模式的连接池,需要实现以下几步
一、创建一个连接池类
二、定义一个连接池容器
三、初始化连接池容器
四、定义取出连接方法
五、定义归还连接方法

连接池的实现

/**
 * @version 1.0
 * @Description 数据库连接池
 * @Author 残冬十九
 * @Date 2020/6/15
 */
public class DbPool {

	/**
	 * 数据库连接池容器
	 */
	private final static LinkedList<Connection> CONNECTION_POOL = new LinkedList<>();

	/**
	 * 初始化连接池,传入初始化大小,当大于0会初始化连接池容器
	 *
	 * @param initialSize
	 */
	public DbPool(int initialSize) {
		if (initialSize > 0) {
			for (int i = 0; i < initialSize; i++) {
				CONNECTION_POOL.addLast(SqlConnectImpl.fetchConnection());
			}
		}
	}

	/**
	 * 获取连接
	 *
	 * @param timeOut 超时时间 ,0或小于0则永不超时。
	 * @return 获取到的连接,超时则为空,需要处理
	 * @throws InterruptedException 抛出的线程状态异常
	 */
	public Connection fetchConn(long timeOut) throws InterruptedException {
		synchronized (CONNECTION_POOL) {
			// 超时时间小于等于0,即为永不超时
			if (timeOut <= 0) {
				// 判断当前线程池是否为空,为空则进入等待状态,等待其他线程来唤醒
				while (CONNECTION_POOL.isEmpty()) {
					CONNECTION_POOL.wait();
				}
				// 获取并返回第一个链接
				return CONNECTION_POOL.removeFirst();
			} else {
				//  求出超时的时间以及剩余的超时时间
				long overtime = System.currentTimeMillis() + timeOut;
				long remain = timeOut;
				// 判断当前线程池是否为空并且剩余超时时间大于0,不满足的进入等待状态,等其他线程唤醒,并且求出剩余超时时间
				while (CONNECTION_POOL.isEmpty() && remain > 0) {
					CONNECTION_POOL.wait(remain);
					remain = overtime - System.currentTimeMillis();
				}
				// 初始化为空的连接,
				Connection connection = null;
				//走到这一步有两种情况,一种是获取到了连接池连接,则获取的连接返回,一种是等待超时,返回空的连接
				if (!CONNECTION_POOL.isEmpty()) {
					connection = CONNECTION_POOL.removeFirst();
				}
				//返回连接
				return connection;
			}
		}
	}

	/**
	 * 放回数据库连接
	 *
	 * @param conn 连接
	 */
	public void releaseConn(Connection conn) {
		//判断连接是否为空
		if (conn != null) {
			synchronized (CONNECTION_POOL) {
				//将连接放入容器尾部
				CONNECTION_POOL.addLast(conn);
				//唤醒所有等待的线程
				CONNECTION_POOL.notifyAll();
			}
		}

	}
}

这就是实现了数据库连接池的类,在类中有
CONNECTION_POOL 连接池容器
DbPool 构造方法来初始化容器
fetchConn 获取连接
releaseConn 归还连接
其中用到的SqlConnectImpl是自定义的一个类,实现了Connection接口,没有做其他处理

public class SqlConnectImpl implements Connection {


	/**
	 * 拿一个数据库连接
	 *
	 * @return
	 */
	public static Connection fetchConnection() {
		return new SqlConnectImpl();
	}
}	

从代码中可以看出我们使用了wait()和notifyAll()方法,这两个方法是我们实现等待超时模式的关键点,wait是让线程处于等待状态,要么是等待时间到了或者被其他线程唤醒,否则会一直等待下去,正是通过这个机制来完成了等待超时模式的连接池。

连接池测试

现在连接池已经实现了,接下来就是要进行对连接池进行测试了。
我们定义了连接池中连接池大小为10,并定义了CountDownLatch 来控制线程,保证main中的统计最后执行(如果对CountDownLatch 不太了解的,可以看看之前的一篇关于CountDownLatch 的博客链接: 高并发(8)- 线程并发工具类-CountDownLatch.)
然后有100个线程,每个线程操作40次,也就是获取4000次连接,然后统计其中获取到连接的次数和超时的次数,这两个分别用了原子操作类来记录,保证线程的安全。

/**
 * @version 1.0
 * @Description 数据库线程池测试
 * @Author 残冬十九
 * @Date 2020/6/15
 */
public class DbPoolTest {

	/**
	 * 初始化线程池,大小为10
	 */
	static DbPool pool = new DbPool(10);
	/**
	 * 控制器:控制main线程将会等待所有Work结束后才能继续执行
	 */
	static CountDownLatch end;


	public static void main(String[] args) throws InterruptedException {

		// 线程数量
		int threadCount = 100;
		//定义CountDownLatch长度
		end = new CountDownLatch(threadCount);
		//每个线程的操作次数
		int count = 40;
		//计数器:统计可以拿到连接的线程,原子操作,保证线程安全
		AtomicInteger got = new AtomicInteger();
		//计数器:统计没有拿到连接的线程,原子操作,保证线程安全
		AtomicInteger notGot = new AtomicInteger();

		//循环创建线程获取连接
		for (int i = 0; i < threadCount; i++) {
			new Thread(new Worker(count, got, notGot), "worker_" + i).start();
		}
		// main线程在此处等待,等待所有线程执行完毕
		end.await();
		System.out.println("总共尝试了: " + (threadCount * count));
		System.out.println("拿到连接的次数:  " + got);
		System.out.println("没能连接的次数: " + notGot);

	}


	static class Worker implements Runnable {
		int count;
		AtomicInteger got;
		AtomicInteger notGot;

		public Worker(int count, AtomicInteger got, AtomicInteger notGot) {
			this.count = count;
			this.got = got;
			this.notGot = notGot;
		}

		@Override
		public void run() {
			while (count > 0) {
				try {
					// 从线程池中获取连接,如果10ms内无法获取到,将会返回null
					// 分别统计连接获取的数量got和未获取到的数量notGot
					Connection connection = pool.fetchConn(10);
					if (connection != null) {
						try {
							//获取到连接则进行操作
							connection.createStatement();
							connection.commit();
						} finally {
							//最后释放连接,并且成功获取连接数量+1
							pool.releaseConn(connection);
							got.incrementAndGet();
						}
					} else {
						//没有获取到连接则等待超时,未获取到连接数量+1
						notGot.incrementAndGet();
						System.out.println(Thread.currentThread().getName()
								+ "等待超时!");
					}
				} catch (Exception ex) {
				} finally {
					//线程操作数量-1
					count--;
				}
			}
			//线程执行完后执行一次CountDownLatch
			end.countDown();
		}
	}
}

运行结果

从结果图中看出,我们请求了4000次连接池,其中3975次获取到了连接,25次连接超时了。
不管spring还是Mybatis中的来连接池都是类似的实现,不过这个是比较简单的实现,不过原理都是一样的。
这个就是简单的等待超时模式的连接池,希望对读者有帮助。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章