数据库连接池示例

学习多线程期间写的小demo,使用到了一些多线程的知识,countDownLatch、wait、notify、AtomicInteger,以及动态代理(模拟数据库连接)。

在测试的时候可以通过增加获取/释放线程的数量,来模拟实际业务中,对数据库压力逐渐增加的场景,能够观察到随着线程的增加,获取成功的数量会下降的现象。

首先是测试类,其中start这个CountDownLatch是为了让所有需要获取/释放数据库连接的线程同时启动任务。end是为了让所有的线程都完成自己获取/释放的任务数量,保证公平性。

java 复制代码
package com.practice.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 连接池的资源是有限的10
 * 当获取的线程逐渐增加的情况下,未在限定时间内获取到的情况会逐渐增加
 */
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 = 30;
        end = new CountDownLatch(threadCount);
        int count = 20;
        AtomicInteger got = new AtomicInteger();
        AtomicInteger noGot = new AtomicInteger();
        for (int i = 0; i < threadCount; i++) {
            Thread thread = new Thread(new ConnectionRunner(count, got, noGot), "ConnectionRunnerThread");
            thread.start();
        }
        start.countDown();
        end.await();
        System.out.println("total invoke:" + (threadCount * count));
        System.out.println("got connection:" + got);
        System.out.println("no got connection:" + noGot);
    }

    static class ConnectionRunner implements Runnable {
        int count;
        AtomicInteger got;
        AtomicInteger noGot;

        public ConnectionRunner(int count, AtomicInteger got, AtomicInteger noGot) {
            this.count = count;
            this.got = got;
            this.noGot = noGot;
        }

        @Override
        public void run() {
            try {
                start.await();
            } catch (Exception ex) {
            }
            while (count > 0) {
                try {
                    Connection connection = pool.fetchConnection(1000);
                    if (connection != null) {
                        try {
                            connection.createStatment();
                            connection.commit();
                        } finally {
                            pool.releaseConnection(connection);
                            got.incrementAndGet();
                        }
                    } else {
                        noGot.incrementAndGet();
                    }
                } catch (Exception exception) {
                } finally {
                    count--;
                }
            }
            end.countDown();
        }
    }
}

连接池实现类,初始化没什么好说的。释放链接需要注意需要加锁,该类使用的是synchronized同步锁,释放完成,需要通知所有在等待的线程。获取连接方法使用了超时等待的设计,这一设计可以防止在获取连接上阻塞过长的时间,影响系统的吞吐量。

java 复制代码
package com.practice.thread;

import java.util.LinkedList;

public class ConnectionPool {
    private final LinkedList<Connection> pool = new LinkedList<>();

    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);
                pool.notifyAll();
            }
        }
    }

    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;
            }
        }
    }
}

连接接口和代理类

java 复制代码
package com.practice.thread;

public interface Connection {
    void createStatment();

    void commit();
}
java 复制代码
package com.practice.thread;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.TimeUnit;

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")){
                TimeUnit.MILLISECONDS.sleep(100);
            }
            return null;
        }
    }

    public static final Connection createConnection(){
        return (Connection)Proxy.newProxyInstance(ConnectionPool.class.getClassLoader(), new Class<?>[]{Connection.class},new ConnectionHandler());
    }
}
相关推荐
_Minato_3 分钟前
数据库知识整理——数据库设计的步骤
数据库·经验分享·笔记·软考
坐吃山猪22 分钟前
BrowserUse14-源码-ScreenShot模块-整理
linux·数据库·python
廋到被风吹走30 分钟前
【数据库】【MySQL】各种 JOIN 的特点及应用场景
数据库·mysql
@nengdoudou31 分钟前
KingbaseES 实现 MySQL 函数 DATEDIFF
数据库·mysql
Knight_AL1 小时前
如何在 MySQL 中优雅统计“只算周一到周五”的到访数据?
数据库·mysql
咸蛋Superman1 小时前
车联网时序数据库靠谱的供应商是哪家
数据库·时序数据库
weixin_462446231 小时前
一键修复 Redis + OpenVAS 权限和启动问题
数据库·redis·bootstrap
咸蛋Superman2 小时前
靠谱的车联网时序数据库服务商有哪些
数据库·时序数据库
AIHE-TECH2 小时前
多台西门子PLC控制器与SQL数据库对接(带边缘计算)的案例
数据库·sql·mysql·边缘计算·达梦数据库·西门子plc·智能网关
思成不止于此2 小时前
【MySQL 零基础入门】MySQL 函数精讲(二):日期函数与流程控制函数篇
android·数据库·笔记·sql·学习·mysql