我有一个servlet,在其中获得一个Connection对象,然后将其交给两个工作线程进行各种 Activity 。我现在需要在一个线程上添加一个事务。
如果我这样开始交易:
connection.setAutoCommit(false);
这会影响两个线程吗?我想会的。
我是否必须获得每个线程的单独连接?
谢谢
最佳答案
我认为您正在做的事情是非常不好的做法。您不能在线程之间共享JDBC连接。
如果您在应用程序服务器(例如TOMCAT/JBoss/WebSphere/WebLogic)下运行,请使用适当的数据源来获取所需的连接。
查看您的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
设置为在单独的连接对象上所需的任何值。
关于multithreading - 跨线程共享的连接的JDBC自动提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5110515/