java MySQL 连接器/JDBC 线程安全吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1209693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:38:39  来源:igfitidea点击:

Is MySQL Connector/JDBC thread safe?

javamysqljdbcconcurrencythread-safety

提问by Emil H

Is the standard MySQL JDBC driver thread-safe? Specifically I want to use a single connection across all threads, but each statement will only be used in a single thread. Are there certain scenarios that are safe and others that aren't? What's your experience here?

标准的 MySQL JDBC 驱动程序线程安全吗?具体来说,我想在所有线程中使用单个连接,但每个语句只会在单个线程中使用。是否有某些情况是安全的,而另一些则不安全?你在这里有什么体验?

采纳答案by ChssPly76

Transactions are started / committed per connection. Unless you're doing some very specific stuff (I can't really think of an example where that would be justified to be honest), you're better off with a connection pool and connection per thread.

每个连接启动/提交事务。除非你正在做一些非常具体的事情(我真的想不出一个诚实的例子),你最好使用连接池和每个线程的连接。

回答by ChssPly76

If autocommit = 1, then it is very feasible to have multiple threads share the same connection, provided the access to the connection is synchronized. If autocommit = 0, you will have to control access to the connection via some sort of mutex until the commit happens.

如果 autocommit = 1,那么多个线程共享同一个连接是非常可行的,前提是对连接的访问​​是同步的。如果 autocommit = 0,您将必须通过某种互斥锁控制对连接的访问​​,直到提交发生。

Unless you absolutely are limited in the amount of connections your application can have, a connection pool may be a more viable alternative.

除非您的应用程序可以拥有的连接数量绝对受到限制,否则连接池可能是更可行的替代方案。

回答by Alex

Based on my recent experience, Connectionobject is not thread safe in Connector/J 5.1.33.

根据我最近的经验,Connection对象在 Connector/J 5.1.33 中不是线程安全的。

I've ran into a deadlock situation described in bug 67760. Not sure if it is a bug, but one reasonable advice from the discussion was:

我遇到了错误 67760 中描述的死锁情况。不确定这是否是一个错误,但讨论中的一个合理建议是:

[12 Dec 2012 20:33] Todd Farmer

Please do not use a single Connection object across multiple threads without proper synchronization. Connector/J - and more importantly, the MySQL client-server protocol - does not allow for concurrent operations using the same Connection object. If a Connection object must be shared across threads, it is the responsibility of the application code author to ensure operations are properly serialized.

[2012 年 12 月 12 日 20:33] 托德·法默

请不要在没有适当同步的情况下跨多个线程使用单个 Connection 对象。Connector/J - 更重要的是,MySQL 客户端-服务器协议 - 不允许使用相同的 Connection 对象进行并发操作。如果必须跨线程共享 Connection 对象,则应用程序代码作者有责任确保操作正确序列化。