Asynchrous calls cause StaleObjectStateException

Posted by Mulone on Stack Overflow See other posts from Stack Overflow or by Mulone
Published on 2010-05-24T12:16:21Z Indexed on 2010/05/24 12:21 UTC
Read the original article Hit count: 230

Hi all, I'm struggling with a Grails service. The service gets AJAX calls from the clients and behaves like a simple local cache for remote objects:

void **someCallFromClient**() {
  // extract params
  def results = remoteService.queryService(params)
  results.each{
      // try to fetch result object from local DB
      def obj = SomeClass.findBySomeField(result.someField)
      if (!obj){
         obj = new Result(params)
         obj.save()
      }

      // do stuff on obj
  }
}

The service works fine when only one client is connected, but as soon as 2 or more clients start bombing the server with requests, I start getting:

    2010-05-24 13:09:49,764 [30893094@qtp-26315919-2] ERROR errors.GrailsExceptionResolver 
 - Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [ some object #892901]
    org.hibernate.StaleObjectStateException: 
Row was updated or deleted by another transaction 
(or unsaved-value mapping was incorrect): [ some object #892901]
    // very long stactrace

It probably happens when 2 calls are trying to create the same object concurrently. I suppose this is a rather typical situation to end up in. Could you recommend any pattern/good practice to fix this issue? For example, is there a way to say to one of the service instances to hang on and wait for the other to finish its stuff and try again?

Cheers!

© Stack Overflow or respective owner

Related posts about hibernate

Related posts about grails