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

serj_ do-not-reply at jboss.com
Fri Jul 20 15:25:55 EDT 2007


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



More information about the jboss-user mailing list