Lock in java - Optimistic and pessimistic

I just tried to understand the optimistic and pessimistic locking mechanisms and came across their definition in https://en.wikipedia.org/wiki/Lock_ (database)

If I try to associate concepts with java instead of a database, can I say that synchronized use is always pessimistic, while using CAS ( AtomicInteger and other classes) is always optimistic?

+5
source share
1 answer

I correctly say that synchronized use is always pessimistic and the use of CAS ( AtomicInteger and other classes) is always optimistic

Yes you are right.

Traditional locking mechanisms, for example. using a synchronized keyword in java is called a pessimistic method of blocking or multithreading.

An optimistic approach is similar to the old adage: “It’s easier to get forgiveness than permission,” where “easier” here means “more effective”. CAS is an example of an optimistic method. StampedLock also supports optimistic locking.

+3
source

Source: https://habr.com/ru/post/1232347/


All Articles