0

Is it a good idea to re-use java.sql.Statement object to execute multiple queries in multiple threads simultaneously?

I've read somewhere that it's recommended to reuse same statement object, however it was sequential execution.

Statement statement = con.createStatement();

Now if I use this single statement instance to run executeUpdate() for multiple queries in multiple threads simultaneously?

Note that it's not PreparedStatement and I am not getting any ResultSet.

I think answer depends on two scenarios:

  1. If queries are mutually exclusive, then it should be okay.
  2. If queries are working on same set of data, then there may be issues.

Is my understanding correct?

Thanks.

1 Answer 1

2

No, it's definitely not a good idea. For one, ResultSets are associated with a Statement. You don't want to be iterating through a ResultSet when another thread suddenly makes a new query (the ResultSet would be closed, at least if the driver is a well behaved one).

There is also nowhere an indication that Statements would be thread-safe. If it's not clearly indicated, it's not thread-safe (at least in most cases).

3
  • Thanks. What if it's not a PreparedStatement and there is no ResultSet? It's just update, delete, insert queries and those are mutually exclusive queries? Commented Aug 7, 2014 at 9:55
  • 2
    @Kayaman: As you said yourself, there is no thread-safety guarantee, so it’s no matter of the driver being “well behaved” when it comes to closing an old ResultSet in a concurrent scenario. There is not even a definition of “old” then. Besides all other possible behavior a thread might receive the ResultSet of the other thread’s query. Commented Aug 7, 2014 at 9:56
  • 2
    @ankur: Simply don’t do it. There is not even a guaranty that a JDBC driver supports multi-threading when using multiple Statements. You have to study the specific driver’s documentation to learn about it’s multi-threading capabilities. Commented Aug 7, 2014 at 9:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.