Java Mailing List Archive

http://www.junlu.com/

Home » Home (12/2007) » JBoss User Help »

[jboss-user] [EJB/JBoss] - how can avoid OptimisticLockException

scott.stark@jboss.org

2007-07-20


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;
|  }
|
|

View the original post : http://www.jboss.com/index.html?module=bb&op=viewtopic&p=4066316#4066316

Reply to the post : http://www.jboss.com/index.html?module=bb&op=posting&mode=reply&p=4066316
_______________________________________________
jboss-user mailing list
jboss-user@(protected)
https://lists.jboss.org/mailman/listinfo/jboss-user
©2008 junlu.com - Jax Systems, LLC, U.S.A.