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.
Best Solution
In my opinion you should NEVER share domains objects across threads. In fact I typically share very little between threads as such data must be protected. I have built some large/high performance systems and have never had to break this rule. If you need to parallelize work then do so but NOT by sharing instances of domain objects. Each thread should read data from the database, operate on it by mutating/creating objects and then commit/rollback the transaction. Work pass in/out should be value/readonly objects generally.