Pavel Bortnovskiy <pbortnovs...@jefferies.com> writes:

> Hello:
>
> Is it safe to call .addBatch() and .executeBatch() methods from
> multiple threads on the same PreparedStatement?
>
> Simple example: batching and executing a large number of the same
> statements (with the same PreparedStatement) by using ExecutorService.

Hi Pavel,

Both addBatch() and executeBatch() do their work in a block synchronized
on the connection, so in theory it should work to have many threads
adding batches to the same PreparedStatement. I don't think it has been
heavily tested, though.

And if the threads set any parameters on the PreparedStatement, your
application needs to synchronize the threads manually. For example, if
two threads call

  ps.setInt(1, id);
  ps.setObject(2, value);
  ps.addBatch();

on the same statement, you need to add synchronization to ensure that
the addBatch() call in one thread doesn't end up using one or more
parameter values set by the other thread.

-- 
Knut Anders

Reply via email to