Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is executeUpdate method in Java a thread-safe one? [duplicate]

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?

like image 666
Alex Avatar asked Mar 14 '13 05:03

Alex


People also ask

How do I know if a method is thread-safe?

A method will be thread safe if it uses the synchronized keyword in its declaration.

Are synchronized methods thread-safe?

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.

Are method arguments thread-safe?

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.

Is clone 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.


1 Answers

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.

like image 92
Sergey Kalinichenko Avatar answered Sep 30 '22 16:09

Sergey Kalinichenko