I was just trying to understand optimistic and pessimistic locking mechanisms and came across the definition of them at https://en.wikipedia.org/wiki/Lock_(database)
If I try to relate the concepts to java instead of a database, am I right in saying that a synchronized usage is always pessimistic and a CAS (AtomicInteger
and other classes) usage is always optimistic?
There are two models for locking data in a database: Optimistic locking , where a record is locked only when changes are committed to the database. Pessimistic locking , where a record is locked while it is edited.
An application under optimistic locking creates a document only when the document does not exist and updates or deletes a document only when the document has not changed since this application last changed it. However, optimistic locking does not actually involve placing a lock on an object.
Pessimistic concurrency control (or pessimistic locking) is called “pessimistic” because the system assumes the worst — it assumes that two or more users will want to update the same record at the same time, and then prevents that possibility by locking the record, no matter how unlikely conflicts actually are.
Optimistic concurrency control is based on the idea of conflicts and transaction restart while pessimistic concurrency control uses locking as the basic serialization mechanism. Analytic and simulation models of both mechanisms were developed in order to compare them as far as transaction response time is concerned.
Am I right in saying that a synchronized usage is always pessimistic and a CAS (
AtomicInteger
and other classes) usage is always optimistic ?
Yes you are correct.
Traditional locking mechanisms e.g. using synchronized keyword in java, is said to be pessimistic technique of locking or multi-threading.
The optimistic approach is like the old saying, “It is easier to obtain forgiveness than permission”, where “easier” here means “more efficient”. CAS is an example of optimistic technique. StampedLock also has support for optimistic locking.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With