跨线程共享连接的 JDBC 自动提交
我有一个 Servlet,在其中获取一个 Connection 对象,然后将该对象传递给两个工作线程以进行各种活动。我现在需要在一个线程上添加一项事务。
如果我开始这样的交易: 连接.setAutoCommit(假);
这会影响两个线程吗?我想会的。
我是否必须为每个线程建立单独的连接?
谢谢
I have a servlet where I get a Connection object which is then handed to two worker threads for various activities. I now need to add a transaction on one thread.
If I start a transaction like this:
connection.setAutoCommit(false);
would that impact both threads? I think it would.
Do I have to get a separate connection of each thread?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你所做的事情是非常糟糕的做法。您不能在线程之间共享 JDBC 连接。
如果您在应用程序服务器(如 TOMCAT/JBoss/WebSphere/WebLogic)下运行,请使用适当的数据源来根据需要获取连接。
查看应用程序服务器文档以获取有关如何执行此操作的信息。
您的 servlet 中将有类似的内容:
同样,您的工作线程将有类似的内容:
最终,您可以将
自动提交
设置为单独连接对象上所需的任何内容。I think what you are doing is very bad practice. You can't share a JDBC connection among threads.
If you are running under an application server (like TOMCAT/JBoss/WebSphere/WebLogic) use a proper DataSource to get your connections as you need them.
Look at your Application Server documentation to get information on how to do that.
You will have something like this in your servlet:
Similarly, your worker threads will have something like:
Eventually, you could set
auto commit
to whatever you need on separate connection objects.