(Quick Reference)

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 provides lock 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 by id.
  • 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 }

See also Optimistic and Pessimistic locking and lock method of domain class.

onNotFound is optional

If you don't have nothing to do on target not found, you can omit onNotFound.

SampleDomain.withPessimisticLock(id) { Object lockedDomain ->
    // …
}

In this case, when target isn't found, all the plugin has to do is nothing.

Closure arguments

The lockedDomain 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
}

The domainId argument of 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 via returnValue property.

def result = SampleDomain.withPessimisticLock(id) { Object lockedDomain ->
    return "OK"
}.onNotFound { ->
    return "NG"
}
assert result.returnValue == "OK"

In case that no row is found, a return value of onNotFound's closure is returned.

assert result.returnValue == "NG"

Transaction is required

When you want to use a pessimistic lock, you must need a transaction. The aquired lock is automatically released when the transaction commits.