Skip to main content

Optimistic and Pessimistic Locking, @Version and Deadlock Handling

Learn Optimistic and Pessimistic Locking, @Version and Deadlock Handling (Phase 8 · Transactions and Concurrency (Core), Hibernate) with worked examples, diagrams and interview questions. Free on JavaSchoolLab.

Lost updates and optimistic locking • Lost update : two users load the same row, both change it, the second commit overwrites the first without noticing. Optimistic locking assumes conflicts are rare: add a @Version field ( int / long / Instant ); Hibernate adds where id=? and version=? to every UPDATE/DELETE and increments the version. If 0 rows are updated, someone else changed it: OptimisticLockException (Spring: ObjectOptimisticLockingFailureException ). • No database locks are held: great scalability, ideal for web apps with user think time. Handle the exception: retry (for system...

More lessons in Phase 8 · Transactions and Concurrency (Core)