title: How should one handle a javax.persistence.OptimisticLockException?
body: <p>I'm new to JPA so forgive me if not being clear.</p>
  
  <p>Basically I want to prevent concurrent modifications by using Optimistic Locking.
  I've added the @Version attribute to my entity class.</p>
  
  <p>I need to know if this algorithm on handling OptimisticLockException is sound.
  I'm going to use the <a href="https://stackoverflow.com/questions/341971/what-is-the-execute-around-idiom">Execute Around Idiom</a> like so:</p>
  
  <pre><code>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();
      }
  }
  </code></pre>
  
  <p>The question I have is how do you decide when to stop retrying ?</p>