连接池和Thread.interrupt()

罗伯特·韦德斯

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

最近,我需要直接或间接使用c3p0在此类线程上实现中断离子处理,并注意到,如果interrupt()c3p0Datasource.getConnection()尝试Connection从池中获取a时调用该方法,则会抛出InterruptedException

显然,发生这种情况是因为 wait()

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

凉爽的。问题是如何正确处理-两种情况都是:a)您想在线程终止之前继续事务,b)您想中止。

我已经尝试了一种看起来效果很好的解决方案(作为答案发布)-实际上,我认为该主题已经关闭。随意加入,谢谢!

罗伯特·韦德斯

我做了一个简单的测试,方法是Connection在1秒钟内发出很多请求,每次tim都要执行一次SELECT,以确保池瓶颈,然后调用interrupt()

我发现的是,即使堆栈跟踪显示我在c3p0崩溃,该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();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章