Is executeUpdate method in Java thread-safe

2020-03-31 03:06发布

问题:

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

回答1:

No, it is not thread-safe to use.

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."

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

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.



回答2:

Consider making your update methods using a synchronized keyword and think about your concurrency threads deadlocks there