Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding Thread safety and JPA EntityManager

Suppose we have two entities dependant to each other and DAOs for each of them

Entity1 -> * Entity2
Entity2 

now suppose we have two threads that are pulling some data from database, Thread1 asks Entity1Dao to get some object with dependant fields initialized, meanwhile Thread2 tries to get same Entity2 objects (already retrieved) with Entity2Dao.

Entity1Dao creates EntityManager (em1) and retrieves data, and Entity2Dao will create different EntityManager (em2) to get queries objects from database.

QUESTION: Does em2 stay locked until em1 get closed? if not should we get exception on "other entitymanager containing requested object"?

like image 797
vach Avatar asked Dec 14 '25 13:12

vach


2 Answers

No. Every EntityManager will return different instances of the entities.

The concurrent transactions will then, potentially, write to the same rows, and the last one will win, unless you implement optimistic concurrency (by adding an @Version field to your entities).

like image 74
JB Nizet Avatar answered Dec 16 '25 01:12

JB Nizet


The entity managers are totally independent in this case. There are mechanisms of optimistic locking and pessimistic locking offered by JPA that you could use to coordinate what should happen during two transaction dealing with the same data.

See the JPA 2.1 Specification, section 3.4 about Locking and Concurrency.

like image 22
Edwin Dalorzo Avatar answered Dec 16 '25 02:12

Edwin Dalorzo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!