使用等待超时模式写一个简单的数据库连接池

本文介绍了如何使用等待超时模式来创建一个简单的数据库连接池。通过设置超时时间T,当达到now+T时,系统判断是否超时。伪代码展示了等待超时模式的工作原理。在实现的ConnectionDriver、ConnectionPool和ConnectionPoolTest类中,随着客户端线程数量增加,超时无法获取连接的情况增多,但线程不会无限等待,而是会及时返回错误信息,起到了系统保护的作用。
摘要由CSDN通过智能技术生成

等待超时模式

假设超时时间是T,那么可以推断出在当前时间 now+T 之后就会超时
定义如下变量

  1. 等待持续时间:REMAINING = T
  2. 超时时间: FUTURE=now+T

这是仅需要wait(REMAINING)即可,在wait(REMAINING)返回之后将会执行: REMAINING = FUTURE-now. 如果REMAINING小于等于0,表示已经超时,直接退出,否则将继续执行 wait(REMAINING).

上述描述等待超时模式的伪代码如下

 public synchronized Object get(long mills) throws InterruptedException{
        long future = System.currentTimeMillis() + mills;
        long remaining = mills;
        while((result == null) && remaining > 0){
            wait(remaining);
            remaining = future - System.currentTimeMillis();
        }
        return result;
    }

接下来写一个简单的数据库连接池示例:

类 ConnectionDriver

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

/**
 * @author chendong
 * @date 2019/9/5 22:25
 */
public class ConnectionDriver {
    static class ConnectionHandler implements InvocationHandler{

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if(method.getName().equalsIgnoreCase("commit")){
                TimeUnit.MILLISECONDS.sleep(100);
            }
            return null;
        }
    }

    public static final Connection createConnection(){
        return (Connection) Proxy.newProxyInstance(ConnectionDriver.class.getClassLoader(), new Class<?>[]{Connection.class}, new ConnectionHandler());
    }

}

类 ConnectionPool

import java.sql.Connection;
import java.util.LinkedList;

/**
 * @author chendong
 * @date 2019/9/5 22:28
 */
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);
                pool.notifyAll();
            }
        }
    }

    // 在mills 之内无法获取到链接,将会返回null
    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;
            }
        }
    }
}

类 ConnectionPoolTest

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @author chendong
 * @date 2019/9/5 22:36
 */
public class ConnectionPoolTest {

    static ConnectionPool pool = new ConnectionPool(10);
    // 保证所有ConnectionRunner能够同时开始
    static CountDownLatch start = new CountDownLatch(1);
    // main线程将会等待所有ConnectionRunner结束后才能继续执行
    static CountDownLatch end;

    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 {
                    // 从线程池获取连接,如果1000ms内无法获取到,将会返回null
                    // 分别统计链接获取的数量 got和为获取的数量notGot
                    Connection connection = pool.fetchConnection(1000);
                    if(connection != null){
                        try {
                            connection.createStatement();
                            connection.commit();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        } finally {
                            pool.releaseConnection(connection);
                            got.incrementAndGet();
                        }

                    }else {
                        notGot.incrementAndGet();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    count--;
                }
            }
            end.countDown();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int threadCount = 30;
        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(); // 使所有线程同时执行
        end.await();
        System.out.println("total invoke: " + threadCount*count);
        System.out.println("got connection: " + got);
        System.out.println("not got connection: " + notGot);
    }   
}

输出结果

threadCountinvokegotnot got
10200200
2040038911
3060054951

我们通过修改threadCount的值,可以看出随着客户端线程的逐渐增加,客户端出现超时无法获取连接的比例不断升高。但是线程是不会一直挂在连接获取的请求上,而是按时返回。并告知客户端连接获取出现问题,是系统的一种自我保护措施。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值