简体   繁体   English

连接池

[英]Connection Pool

 BlockingQueue<Connection> connections = new LinkedBlockingQueue<Connection>(maxConnection);

AtomicInteger numberOfDrewedConnectionFromPool

In my ConnectionPool i use LinkedBlockingQueue.在我的 ConnectionPool 中,我使用 LinkedBlockingQueue。 I have some doubt whether multiply "if statement" will be thread-safe.我怀疑乘法“if语句”是否是线程安全的。 maxConnection is constant. maxConnection 是恒定的。 numberOfDrewedConnectionFromPool changes also in method releaseConection without lock().. numberOfDrewedConnectionFromPool 在方法 releaseConection 中也发生了变化,没有 lock()..

 public Connection getConnection() throws ConnectionPoolException {
    Connection connection = null;

    if ((connections.poll() == null) && (maxConnection > numberOfDrewedConnectionFromPool.get())) {
        return newConnection();
    } else {
        return connections.poll();
    }
}


private Connection newConnection() throws ConnectionPoolException {
    lock.lock();
    Connection connection = null;
    try {
        try {
            connection = DriverManager.getConnection(url, user, password);
            numberOfDrewedConnectionFromPool.incrementAndGet();
        } catch (SQLException exception) {
            throw new ConnectionPoolException();
        }
    } finally {
        lock.unlock();
        return connection;
    }

}

No, your code is not thread-safe.不,您的代码不是线程安全的。

Between the time where connections.poll() is called and the time where the number of connections is compared to the max, some other thread might have released or taken a connection, and the number of connections might have changed.在调用connections.poll()数。 Moreover, you're polling the queue twice to get a single connection.此外,您轮询队列两次以获得单个连接。

Side note: why are you reinventing the wheel?旁注:你为什么要重新发明轮子? There are plenty of free connection pools available.有很多免费的连接池可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM