7.3.5 Pessimistic and Optimistic Locking - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari
Version: 3.1.10
7.3.5 Pessimistic and Optimistic Locking
Optimistic Locking
By default GORM classes are configured for optimistic locking. Optimistic locking is a feature of Hibernate which involves storing a version value in a specialversion
column in the database that is incremented after each update.The version
column gets read into a version
property that contains the current versioned state of persistent instance which you can access:def airport = Airport.get(10)println airport.version
def airport = Airport.get(10)try { airport.name = "Heathrow" airport.save(flush: true) } catch (org.springframework.dao.OptimisticLockingFailureException e) { // deal with exception }
The version
will only be updated after flushing the session.
Pessimistic Locking
Pessimistic locking is equivalent to doing a SQL "SELECT * FOR UPDATE" statement and locking a row in the database. This has the implication that other read operations will be blocking until the lock is released.In Grails pessimistic locking is performed on an existing instance with the lock method:def airport = Airport.get(10) airport.lock() // lock for update airport.name = "Heathrow" airport.save()
get()
and the call to lock()
.To get around this problem you can use the static lock method that takes an id just like get:def airport = Airport.lock(10) // lock for update airport.name = "Heathrow" airport.save()
def airport = Airport.findByName("Heathrow", [lock: true])
def airport = Airport.createCriteria().get {
eq('name', 'Heathrow')
lock true
}