Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locking in java - Optimistic vs Pessimistic

Tags:

java

locking

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?

like image 399
userx Avatar asked Sep 26 '15 11:09

userx


People also ask

What is optimistic and pessimistic locking in Java?

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.

What is optimistic locking in Java?

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.

What is pessimistic locking?

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.

What is the difference between optimistic and pessimistic concurrency?

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.


1 Answers

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.

like image 177
akhil_mittal Avatar answered Oct 16 '22 17:10

akhil_mittal