API / Apache Grails Interview questions
Explain how GORM's optimistic locking prevents concurrent update conflicts?
Optimistic locking assumes conflicts are rare and checks for them only at save time, rather than locking a row the moment it's read (as pessimistic locking would) — GORM implements this automatically through the version property every domain class gets by default.
Every time a record is loaded, its current version number comes along with it; when a save happens, GORM's generated SQL includes a WHERE version = <the value it was loaded with> clause and, on success, increments the stored version. If two users load the same record, and the first one saves successfully (bumping the version), the second user's later save attempt matches zero rows — because the version they're checking against is now stale — and GORM surfaces that as an OptimisticLockingFailureException rather than silently letting the second save overwrite the first user's changes.
This gives an application a reliable way to detect (and typically prompt the user to resolve) a genuine conflicting-edit scenario, without paying the cost of holding a database lock on every record for the entire time it's being viewed or edited, which is the trade-off pessimistic locking would otherwise impose.
More Related questions...