synchronized block on grails works on windows but no in linux

六月ゝ 毕业季﹏ 提交于 2019-12-01 14:45:09

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)

Espero que ajude.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!