In my application,there are multiple threads trying to insert to a MySQL database.Is executeUpdate method thread-safe to use?How can I make this work?
A method will be thread safe if it uses the synchronized keyword in its declaration.
Thread safe means: method becomes safe to be accessed by multiple threads without any problem at the same time. synchronized keyword is one of the way to achieve 'thread safe'. But Remember:Actually while multiple threads tries to access synchronized method they follow the order so becomes safe to access.
Each thread executing the sharedMethod() method will make use of its own Object o as parameter. So, the whole method sharedMethod() seems to be thread safe.
No it is not thread safe if two threads are trying to execute this method over the same instance of Foo. You should create a mutex using this instance . For example place the code which executes this clone method in synchronized(fooInstance) block.
While executeUpdate
method in itself may be thread safe, prepared statements are not designed to be used concurrently. This is because each instance stores your parameters until executeUpdate
instructs it to send the parameters to MySQL. Moreover, since transactions are managed through Connection
objects, sharing connections concurrently without synchronization may give you undesired behavior on commits/rollbacks.
In order to make inserts from multiple threads work concurrently, each thread needs to use its own Connection
, and make its own PreparedStatement
. Using multiple prepared statements concurrently on the same database is thread safe, because the concurrency is managed on the RDBMS side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With