0 Replies Latest reply on Jul 20, 2007 3:25 PM by serj f

    how can avoid OptimisticLockException

    serj f Newbie

      hello,
      I don't know how to solve concurrency problems in a nice way. To fix my updating code I set version control for entity and I check if get OptimisticLockException.

      I think this is not the best solution, so I wish to know what is a beter solution for this classic case. I think I should get a record, lock it, update fields and unluck it ... but I don't know how to do it.

      Thanks a lot for help


      My code for update looks like this (strange enough for only one update):

       while(true){
       boolean ok = true;
       Balance balance = testSessionA.getBalance(id,sleepTime);//sleep used just for testing
       balance.setAmount(balance.getAmount()+10);
       try{
       testSessionA.update(balance);
       }catch(javax.ejb.EJBException ex){
       ex.printStackTrace();
       if(ex.getMessage().equals("javax.persistence.OptimisticLockException")){
       //how many times we should try to update??
       ok = false;
       }
       }
       if(ok){
       break;
       }
       }
      
      


      I have a stateless session bean,

      @Stateless
      @Remote(TestSessionA.class)
      @Local(TestSessionA.class)
      public class TestSessionABean implements TestSessionA{
      
       public Balance getBalance(long bId, long sleepTime) throws Exception {
       Balance b = em.find(Balance.class, bId);
       Thread.sleep(sleepTime);//use sleep just to test
       return b;
       }
      
       public void update(Balance balance) {
       em.merge(balance);
      
       }
      
      


      and Balance entity have version controll:
      @Entity
      public class Balance implements Serializable{
      
       @Version
       @Column(name = "OPTLOCK")
       public int getVersion() {
       return version;
       }