It seems like most examples of JPA/Hibernate entity bean classes I’ve seen do no explicit synchronization. Yet, it is possible to call getters/setters on those objects in the context of building up a transaction. And it’s possible for those methods to be called across multiple threads (although maybe that’s unusual and weird).
It seems like if it is built up across multiple threads then it’s possible for changes to object state to be lost, which would be sad.
So, is leaving out synchronization best practice? Is the Hibernate instrumented code taking care of proper synchronization for me?
As an example:
@Entity public class Ninja { @Id @GeneratedValue private Long id; @Column private String name; @Column private int throwingStars; public Ninja() {} public int getThrowingStars() { return throwingStars; } public void addThrowingStar() { throwingStars += 1; } }
Do the throwing star methods need synchronization? I sure don’t want my ninja to lose any throwing stars.
The object probably is not the same for the 2 threads. Supposing your threads use a session factory to access the db, the objects you get from the session should be viewed as ‘independent’ (I believe hibernate creates ‘fresh’ objects for each get(), unless they are in the session).
As for your stars question, it’s the same when two persons fetch the same row from a DB, the DB ‘ACID’ properties will make sure that each operation is atomic, so if you remove a star from a ninja in Thread t1 and commit, Thread t2 will read the committed values of t1.
Alternatively, you can ask hibernate to lock the row of the relevant ninja in T1, so that even if T2 asks for the row it will have to wait until T1 commits or aborts.