我有一个场景,当一个对象被2个不同线程更新时。以下是grails服务类中的代码。我能够捕获StaleObject异常,但是当我尝试从数据库中再次获取并重试保存值时,它不起作用。处理服务中的StaleObjectException
public long updateTimer(Long timeLeft, TestAttempted testAttempted){
// Let's say testAttempted.version() is now 5
// It is concurrently updated by other thread, version is now 6
........
............
testAttempted.setTimer(someCalculatedValue)
try{
testAttempted.save(failOnError: true,flush:true) // StaleObject exception occurs
}catch(OptimisticLockingFailureException e){
testAttempted.refresh()
testAttempted.setTimer(someCalculatedValue)
testAttempted.save(failOnError:true)
}
}
为什么上面的代码不会更新/保存catch块中的值?我也尝试TestAttempted.get(id)方法从数据库中获取最新的一个,但它不起作用。
但是当我尝试这一点,更新最新的定时器值:
在控制器: -
try{
timeLeft = assessmentService.updateTimer(timeLeft,testAttempted)
}catch(OptimisticLockingFailureException e){
testAttempted = TestAttempted.get(session['testAttemptedId'])
........
testAttempted.setTimer(someCalculatedValue)
testAttempted.save(failOnError: true)
}
在服务:
public long updateTimer(Long timeLeft, TestAttempted testAttempted){
........
.................
testAttempted.setTimer(someValue)
testAttempted.save(failOnError: true)
return timeLeft
}
它不工作,如果它被抛出并在控制器/服务中处理。它在投入使用并在控制器中处理时起作用。这怎么可能 ?
感谢您的回复。实际上这两个线程都会更新不同的字段。他们从不更新公共领域。所以我认为放下版本领域应该更合适。不是吗? –
如果您没有任何其他代码可以更新此域并依赖乐观锁定,那么是的 - 只需关闭域的版本控制即可。 – Yaro