每个线程在新连接实例上的连接池(JDBC) [英] Connection Pooling over New Connection instance per Thread (JDBC)

查看:199
本文介绍了每个线程在新连接实例上的连接池(JDBC)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个多线程应用程序.但是,当我有一个为所有线程服务的连接对象时,我的应用程序遇到了许多意外行为.

I am creating a multi-threaded application. However, I have experienced lots of unexpected behavior from my application when I have one connection object serving all threads.

我处于两难境地.我应该让每个线程创建,使用和处置其自己的连接对象还是应该使用连接池?

I am in a dilemma. Should I let every thread create, use and dispose its own connection object or should I use a connection pool?

我尝试了连接池,这会使应用程序痛苦地洗澡.但是,我的直觉是,如果让每个线程创建自己的连接对象,则可能会出现连接过多"错误.

I have tried connection pooling which makes the application painfully shower. However, my intuition is that if I let every thread create its own connection object, I might get a "too many connection" error.

请让我知道是否有任何方法可以帮助您.

Please let me know if there is any way to assist in this.

致谢.

推荐答案

无论线程问题如何,您都应该一定使用连接池.它将大大提高连接性能.然后到线程问题,这确实是一个主要问题. JDBC的惯用法是在最短范围内获取 close 所有资源. IE.所有这些都应该在同一方法块中进行.您正在描述的问题症状表明您没有正确关闭这些资源.

Regardless of the threading issue, you should definitely go for a connection pool. It will greatly increase connecting performance. Then to the threading issue, this is indeed a major problem. The normal JDBC idiom is to acquire and close all resources in the shortest possible scope. I.e. all should happen in the very same method block. The problem symptoms which you're describing confirms that you aren't closing those resources properly.

无论连接是否来自池,都应始终执行关闭操作.如果关闭了非池化连接,则当数据库保持打开状态太长时间时,它将防止数据库超时.关闭池化连接实际上会将其释放回池中,并使其可用于下一个租约.

Closing should always happen regardless of whether the connection is coming from a pool or not. Closing a non-pooled connection will prevent it from being timed-out by the database when it's been hold open for a too long time. Closing a pooled connection will actually release it back to the pool and make it available for the next lease.

这是INSERT情况下的普通JDBC惯用法.

Here's how the normal JDBC idiom look like for the case of a INSERT.

public void create(Entity entity) throws SQLException {
    // Declare.
    Connection connection = null;
    PreparedStatement statement = null;

    try { 
        // Acquire.
        connection = database.getConnection();
        statement = connection.prepareStatement(SQL_CREATE);

        // Use.
        statement.setSomeObject(1, entity.getSomeProperty());
        // ...
        statement.executeUpdate();
    } finally {
        // Close.
        if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
        if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
    }
}

这篇关于每个线程在新连接实例上的连接池(JDBC)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆