I have a grails application that relies on a synchronized block into a service. When I run it on windows the synchronization works as expected but when I run on ams linux a
You are right about why you're getting the StaleObjectStateException.
If what you're looking for is pessimistic locking (allowing only one transaction access to the data at any given time), then you can use the domain class lock() method:
class TestService {
static transactional = true
TesteSync incrementa() {
TesteSync t = TesteSync.lock(1)
t.contador++
return t.save()
}
}
You can learn more about Grails pessimistic locking here.
PS: Grails services are transactional by default. But in my example I explicitly made the service transactional to call something to your attention: The lock is released by Grails automatically when the transaction commits. I also removed the flush because the data gets flushed when the transaction commits. If you were doing this from a controller method that's not explicitly set to @Transactional, then you would need the flush.
TIP: When you query by ID you can do this...
SomeDomainClass.get(1)
...instead of this...
SomeDomainClass.findById(1)