title: How to write Java code that is synchronized on an instance of an entity
body: <p>I'm using Hibernate and Spring and I want to write Service code to cater for the scenario where, in two separate threads, a <code>DAO</code> is used to fetch an entity instance by id, and it is the same id / database row in each case, and I don't want a given method to run concurrently in both threads for that entity instance. </p>
  
  <p>I'm not sure whether it is possible to write...</p>
  
  <pre><code>synchronized(entity) {}
  </code></pre>
  
  <p>or whether this is not possible because each thread could have created a different instance of the object in memory when retrieving from the <code>DAO</code>, both referring to the same entity instance.</p>
  
  <p>If indeed it is possible for Hibernate to create multiple objects in memory for the same entity instance, what is the best way to do what I am trying to do?</p>