【问题标题】:JDBC auto commit for connection shared across threads跨线程共享连接的 JDBC 自动提交
【发布时间】:2011-02-24 21:10:21
【问题描述】:

我有一个 servlet,我在其中得到一个 Connection 对象,然后将其交给两个工作线程以进行各种活动。我现在需要在一个线程上添加一个事务。

如果我开始这样的交易: connection.setAutoCommit(false);

这会影响两个线程吗?我想会的。

我必须获得每个线程的单独连接吗?

谢谢

【问题讨论】:

  • 除非在 JDBC 驱动程序手册中明确说明,否则您实际上无法共享连接。

标签: multithreading jdbc autocommit


【解决方案1】:

我认为你正在做的是非常糟糕的做法。您不能在线程之间共享 JDBC 连接。

如果您在应用服务器(如 TOMCAT/JBoss/WebSphere/WebLogic)下运行,请使用适当的 DataSource 来获取所需的连接。

查看您的应用程序服务器文档以获取有关如何执行此操作的信息。

你的 servlet 中会有这样的东西:

public void doGet(HttpServletRequest req, HttpServletResponse resp)
{
    Connection c = null;
    try {
        c = ...; /* preferred way of getting a connection in your AppServer
        // do what you need with your JDBC connection
    } catch (Exception e) {
        // handle errors
    } finally {
        c.close(); /* you will need another TRY/CATCH here */
    }
}

同样,您的工作线程将具有以下内容:

public void run()
{
    Connection c = null;
    try {
        c = ...; /* preferred way of getting a connection in your AppServer
        // do what you need with your JDBC connection
    } catch (Exception e) {
        // handle errors
    } finally {
        c.close(); /* you will need another TRY/CATCH here */
    }
}

最终,您可以在单独的连接对象上将auto commit 设置为您需要的任何内容。

【讨论】:

  • 你说得对。我没有考虑共享连接的影响,所以我正在调整每个线程以获取它自己的连接。
猜你喜欢
  • 1970-01-01
  • 2014-02-22
  • 2010-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 2021-09-12
相关资源
最近更新 更多