2011-02-24 51 views
2

我有一个servlet,我得到一个Connection对象,然后交给两个工作线程进行各种活动。我现在需要在一个线程上添加一个事务。跨线程共享连接的JDBC自动提交

如果我开始这样一个事务: connection.setAutoCommit(false);

会影响两个线程吗?我认为会的。

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

感谢

+0

除非在JDBC驱动程序手册中明确声明,否则实际上不能共享连接。 – bestsss 2011-02-24 21:19:05

回答

1

我觉得你在做什么是非常不好的做法。您不能在线程之间共享JDBC连接。

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

查看您的Application Server文档以获取有关如何执行此操作的信息。

你有这样的事情在你的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到任何你需要在不同的连接对象。

+1

你是对的。我没有考虑共享连接的影响,所以我正在调整每个线程以获取它自己的连接。 – 2011-02-25 14:17:16