3 Pessimistic Locking - Reference Documentation
Authors: Yasuharu NAKANO
Version: 0.4
3 Pessimistic Locking
In order to operate a domain instance on multi-threads sequentially, Grails provideslock
method on domain class.
I know its usage is very easy, but the plugin provides the wrapper way for withPessimisticLock
in the point of view of symmetry for withOptimisticLock
.
withPessimisticLock
static method invoke the closure with the locked domain instance specified byid
.- If target row isn't found,
onNotFound
closure is invoked.
SampleDomain.withPessimisticLock(id) { Object lockedDomain -> // operation to require a pessimistic lock}.onNotFound {domainId -> // operation when the target is not found
}
onNotFound is optional
If you don't have nothing to do on target not found, you can omitonNotFound
.SampleDomain.withPessimisticLock(id) { Object lockedDomain ->
// …
}
Closure arguments
ThelockedDomain
argument of withPessimisticLock
's closure is the domain instance which is found by SampleDomain.lock(id)
method.SampleDomain.withPessimisticLock(id) { Object lockedDomain ->
assert lockedDomain.id == id
}
onNotFound
's closure is the domain id which is specified to withPessimisticLock
's first argument.SampleDomain.withPessimisticLock(id) { Object lockedDomain ->
// …
}.onNotFound {domainId ->
assert domainId == id
}
Return value
If you want a return value from closure, you can receive it viareturnValue
property.def result = SampleDomain.withPessimisticLock(id) { Object lockedDomain -> return "OK" }.onNotFound { -> return "NG" } assert result.returnValue == "OK"
onNotFound
's closure is returned.
assert result.returnValue == "NG"