BlockingQueue<Connection> connections = new LinkedBlockingQueue<Connection>(maxConnection);
AtomicInteger numberOfDrewedConnectionFromPool
在我的ConnectionPool中,我使用LinkedBlockingQueue。我怀疑是否“if语句”是线程安全的。 maxConnection是常量。 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;
}
}
答案 0 :(得分:1)
不,您的代码不是线程安全的。
在调用connections.poll()
的时间与将连接数与max进行比较的时间之间,某些其他线程可能已释放或建立连接,并且连接数可能已更改。
此外,您要轮询队列两次以获得单个连接。
旁注:为什么要重新发明轮子?有很多免费的连接池。