I've got a servlet that does some work with user after which decrement user's credit. After I watch user's credit within the database instantly, if you will find many concurrent demands in the same user, the loan continues to be subtracted improperly because of concurrency control; T
Assume I've one server and database management used is hibernate.
I'm using transaction control to span the entire request, please visit code for detail. I've several questions:
1. how come the loan counter in db jumping everywhere when facing many concurrent request from same user? why is not my transaction control working?
2. if underlying data was modified once i retrieved user account after which make an effort to update it, why did not I recieve any HibernateException(eg.StaleObjectException)?
3. I've transaction span over the full user request, it is possible to better way? please critique. You can rewrite the sample code structure if you think I am doing the entire factor wrong.
Primary servlet class: protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException catch(Exception exp) finally public void cmdDowork() catch (HibernateException e) public static UserAccount lazyGetUserAccount(String userName) return userAccount private boolean decUserAccountQuota(UserAccount userAccount) I did previously test positive securing as recommended through the answer, I'm not obtaining a any StaleObjectException, the update were committed effectively.. Session em1=Manager.sessionFactory.openSession() Session em2=Manager.sessionFactory.openSession()
em1.getTransaction().begin(); em2.getTransaction().begin(); UserAccount c1 = (UserAccount)em1.get( UserAccount.class, "jonathan" ); UserAccount c2 = (UserAccount)em2.get( UserAccount.class, "jonathan" ); c1.setBalance( c1.getBalance() -1 ); em1.flush(); em1.getTransaction().commit(); System.out.println("balance1 is "+c2.getBalance()); c2.setBalance( c2.getBalance() -1 ); em2.flush(); // fail em2.getTransaction().commit(); System.out.println("balance2 is "+c2.getBalance());