July 3, 2016

Optimistic vs Pessimistic Locking in JPA

Issue Optimistic Pessimistic
Deadlocks No
execution goes straight without locking anything in database. Execution may fail if a concurrent thread modified the same record  ( OptimisticLockingException will be throw in this case)
Yes
database-level locks are acquired and hence deadlock may occur
Transaction Span Temporal and spatial span
entity version could be conveyed to client which can hold it as long as he wants. This allow a virtual transaction to span both temporal and spatial. Only during commit version check will be enrolled to ensure data integrity
No span
it would be a suicide to hold a database-level lock on an entity which is edited by client remotely. This would quickly exhaust all system resources. As such no transaction span is available
Changes Overwrite No
changes made to an entity in another thread are detected and transaction is aborted – this prevents unwanted overwrites
Yes
changes made to an entity in another thread are not detected – they are simply overwritten (last change wins)
Changes in Tables Required
need to add column into each table for storing a version counter  ( javax.persistence.Version)
No
everything needed is provided by database itself
Performance Better
doesn’t require and database interactions – recommended for web apps which must scale
Poorer
requires explicit locking in database which is expensive

Links: