1

In a multi-threaded environment, each thread is executing this call() >>

PreparedStatement st1 = null
PreparedStatement st2 = null;

.....
.....

st1.executeBatch();
st2.executeBatch();
connection.commit();

Is it guaranteed that for each thread, the sql batches inside st1 will execute BEFORE the sql batches in st2? In other words, is the synchronous behavior guaranteed in this case?

Thanks

Tintin
  • 2,853
  • 6
  • 42
  • 74
  • 2
    Yes. executeBatch is a blocking operation. It only returns once the batch has been executed, as explained in the javadoc. – JB Nizet Oct 31 '16 at 21:31

1 Answers1

0

According to the documentation, the connection object can have auto-commit mode either enabled (default mode) or disabled. When auto-commit is false:

If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by a call to either the method commit or the method rollback. By default, new connections are in auto-commit mode.

Therefore if auto-commit is false, the first batch will be committed before the second. If auto-commit is true, the first and second batches will be committed as one transaction. Note that Connection.close() should only be used when auto-commit is false.

In both cases, the execution order (regardless of the commit mode) follows the order in the code.

M A
  • 71,713
  • 13
  • 134
  • 174
  • "If autocommit is true, the first and second batches will be committed as one transaction." Even in the "same transaction", the sql inside first statement would execute before sql inside second, correct? [ The order of statements would remain sequential? ] – Tintin Oct 31 '16 at 21:53
  • Yes correct. Seems what you're asking is in http://stackoverflow.com/questions/18859905/jdbc-transaction-execution-order-of-sql-statements. – M A Oct 31 '16 at 21:58