Java线程中的executeUpdate方法是否安全 [英] Is executeUpdate method in Java thread-safe

查看:374
本文介绍了Java线程中的executeUpdate方法是否安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个线程试图更新MySQL数据库? executeUpdate方法使用线程安全吗?

I have multiple threads trying to update a MySQL database? is executeUpdate method thread-safe to use?

推荐答案

否,使用它不是线程安全的.

No, it is not thread-safe to use.

实际上,如果某个其他线程使用一条语句,然后另一个线程调用executeUpdate(),则另一个线程的ResultSet(如果有的话)将被关闭. 用于java.sql.Statement的JavaDoc(PreparedStatement是一个子类型)如果存在已打开的语句,则Statement接口中的所有执行方法都将隐式关闭该语句的当前ResultSet对象."

In fact, if some other thread uses a statement, and then another thread calls executeUpdate(), then the other thread's ResultSets, if any, will be closed. JavaDoc for java.sql.Statement (of which PreparedStatement is a subtype) "All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists."

此外,executeUpdate()的给定实现不太可能被编写为多线程安全的.

Furthermore, it's unlikely that a given implementation of executeUpdate() would be written to be mulit-thread safe.

您应该同步所有对语句和结果集的使用,或者建立多个连接,以便每个线程对数据库使用自己的JDBC Connection.我建议后者.

You should either syncrhonize all use of the statement and resulting result sets, or make multiple connections so that each thread uses its own JDBC Connection to the database.. I would recommend the latter.

这篇关于Java线程中的executeUpdate方法是否安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆