I'm new to JPA so forgive me if not being clear.
Basically I want to prevent concurrent modifications by using Optimistic Locking. I've added the @Version attribute to my entity class.
I need to know if this algorithm on handling OptimisticLockException is sound. I'm going to use the Execute Around Idiom like so:
interface UpdateUnitOfWork
{
doUpdate( User user ); /* may throw javax.persistence.PersistenceException */
}
public boolean exec( EntityManager em, String userid, UpdateUnitOfWork work)
{
User u = em.find( User, userid );
if( u == null )
return;
try
{
work.doUpdate( u );
return true;
}
catch( OptimisticLockException ole )
{
return false;
}
}
public static void main(..) throws Exception
{
EntityManagerFactory emf = ...;
EntityManager em = null;
try
{
em = emf.createEntityManager();
UpdateUnitOfWork uow = new UpdateUnitOfWork() {
public doUpdate( User user )
{
user.setAge( 34 );
}
};
boolean success = exec( em, "petit", uow );
if( success )
return;
// retry 2nd time
success = exec( em, "petit", uow );
if( success )
return;
// retry 3rd time
success = exec( em, "petit", uow );
if( success )
return;
}
finally
{
em.close();
}
}
The question I have is how do you decide when to stop retrying ?