Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

What is the difference between pessimistic concurrency and optimistic concurrency?


Asked by Sky Hansen on Dec 01, 2021 FAQ



Pessimistic Concurrency is a ‘seatbelt in your car’ approach – we assume that concurrency conflicts will happen and we believe they will happen often. It locks database’s record for update access and other users can only access the record as read-only or have to wait for a record to be ‘unlocked’.
Moreover,
To sum up, optimistic locking (or optimistic concurrency control), is a general principle for synchronization w/o locks. MVCC is an optimistic technique which allows isolated transactions which span multiple objects.
Also, Pessimistic concurrency: Assumes that resource conflicts between multiple users are very likely to occur and hence locks resources as they are used by transactions for the duration of the transaction. A transaction is assured of successful completion unless a Deadlock ocurrs.
One may also ask,
Just to rectify Dimos's answer: timestamp based concurrency control is still a pessimistic method (it may still abort/block transactions during their execution phase). Thanks for contributing an answer to Stack Overflow!
Accordingly,
Both pessimistic and optimistic locking are useful techniques. Pessimistic locking is suitable when the cost of retrying a transaction is very high or when contention is so large that many transactions would end up rolling back if optimistic locking were used.