gpt4 book ai didi

java - 连接池和 Thread.interrupt()

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:46:50 33 4
gpt4 key购买 nike

我正在使用 c3p0在多线程环境中处理数据库连接池。这个问题可能与其他池库有关,但这就是我所拥有的。

最近我需要实现 interrupt直接或间接使用 c3p0 对此类线程进行 ionic 处理,并注意到如果在 c3p0Datasource.getConnection() 试图为我获取一个 时调用了 interrupt() >Connection 从池中,它抛出一个 InterruptedException

显然,这是因为 wait()

at java.lang.Object.wait(Native Method)
at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1414)

很酷。问题是您如何正确处理这个问题 - 两种情况都是 a) 您希望在线程终止之前继续处理事务,以及 b) 您想要中止。

我已经尝试了一个似乎工作正常的解决方案(作为答案发布)- 实际上,我认为这个主题已经结束。否则请随意补充,谢谢!

最佳答案

我做了一个简单的测试,在 1 秒内触发了很多 Connection 请求,每次执行 SELECT 确保池瓶颈,然后调用 interrupt().

我发现 connection 对象在 InterruptedException 被捕获后很好用,即使堆栈跟踪显示我在 awaitAvailable(. .)。就在这一刻,我正在检查它们的来源,并且肯定地,它们处理了 InterruptedException。他们甚至会发出适当的警告:

WARNING: com.mchange.v2.resourcepool.BasicResourcePool@5bcf4b61 -- an attempt to checkout a resource was interrupted, and the pool is still live: some other thread must have either interrupted the Thread attempting checkout!

告诉我们它仍然存在,尽管中间有很多词模糊。解决了。

无论如何,这是测试。

ComboPooledDataSource ds = new ComboPooledDataSource();

// testing with various pool sizes - same effect
ds.setMinPoolSize(1);
ds.setMaxPoolSize(5);
ds.setInitialPoolSize(2);

Thread connectingThread = new Thread() {

public void run() {
Connection cnxn = null;
while (true) {
try {
cnxn = ds.getConnection();
System.out.println("Got connection.);
executeQuery(cnxn);
} catch (SQLException e) {
System.out.println("Got exception.");
e.printStackTrace();

// SOLUTION:
Throwable cause = e.getCause();
if (cause instanceof InterruptedException) {
System.out.println("Caught InterruptedException! Cnxn is " + cnxn);

// note that cnxn is a com.mchange.v2.c3p0.impl.NewProxyConnection
// also note that it's perfectly healthy.
//
// You may either want to:
// a) use the cnxn to submit your the query

executeQuery(cnxn);
cnxn.close()

// b) handle a proper shutdown

cnxn.close();

}
break;
}
}
};
};

connectingThread.start();

try {
Thread.sleep(1000);
} catch (InterruptedException e) { e.printStackTrace(); }

connectingThread.interrupt();

关于java - 连接池和 Thread.interrupt(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25952371/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com