tags:

views:

281

answers:

2

Background: I am using hibernate objects for database access.
inside my servlet's doGet I have:

Account account=getUserAccountHibernateObject();
doWorkOnAccount(account);
decreaseAccountBalanceAndSaveToDB(account);

Since servlet allows concurrent access, the accountBalance is really messed up sometimes. I have several questions:

  1. What's the best practice here? Should my thread implement SingleThreadModel to prevent concurrent access? Or synchronize everything in doGet?
  2. Should I do the following? What's the right thing to do in hibernate?

    Account account=getUserAccountHibernateObject();
    doWorkOnAccount(account);
    account=getUserAccountHibernateObject();
    decreaseAccountBalanceAndSaveToDB(account); //also synchronize this method.
    

Edit: tentative solution: thanks to the link provided by the answers, I think I need to span DB transaction throughout the servlet request:

beginTransaction();
try{
Account account=getUserAccountHibernateObject();
doWorkOnAccount(account);
decreaseAccountBalanceAndSaveToDB(account); 
commitTransaction();
}catch(Exception ep){
  rollBackTransaction();
}finally{
   closeSession();
}

if there's any hibernate/db guru out there thing there's something wrong with this, please let me know.

+3  A: 

You want to use Transactions. There's a section of the Hibernate manual that covers this, especially the "Unit of work" part.

skaffman
A: 

My guess is that part of your code stores or accesses data in static variables or is otherwise improperly thread-safe.

I have worked on relatively large webapps which have never needed to provide excessive synchronization (and certainly not resort to single-thread access) to avoid concurrency problems.

It's hard to suggest what specifically to fix without seeing more of how things are laid out.

matt b