This article was compiled by Colodoo (Paper Umbrella)

QQ 425343603

Java Learning Exchange Group (717726984)

There has been heard of optimistic lock and pessimistic lock these two terms, but has not gone to understand him, today specially to search the difference between the two.


Look at the picture to understand

Let’s start with a story to understand these two terms.

A is A kindergarten teacher, and it’s time for children to play with toys. Today, A brought new toys to the children and let the children play together. At the beginning, the children are very orderly and the teacher is also very happy.Happy time is always short, playing, two of the children because of who first play toys cry, the teacher as long as go up to comfort the two crying children.The next day, A gave them A new arrangement based on their performance last time. Let them line up one by one, so that the children should not quarrel.But some children are too playful and do not go all the time. The children behind can only wait, because A does not stipulate the time to play.

conclusion

Pessimistic locking

Always assume the worst, every time to fetch the data that people will change, so every time when take data will be locked, so people want to take this data will be blocked until it got locked (Shared resources to only one thread at a time using, other threads blocked, after use to transfer resources to other threads). Traditional relational database inside used a lot of this locking mechanism, such as row lock, table lock, read lock, write lock, etc., are in the operation before the first lock. Exclusive locks such as synchronized and ReentrantLock in Java are implementations of the pessimistic locking idea.


Optimistic locking

Always assume the best case, every time I go to get the data, I think others will not modify it, so I will not lock it, but when updating, I will judge whether others have updated the data during this period, which can be achieved by using the version number mechanism and CAS algorithm. Optimistic locks are suitable for multi-read applications to improve throughput. Optimistic locks are provided by databases similar to write_condition. In Java. Java util. Concurrent. Atomic package this atomic variable classes is to use the optimistic locking a way of implementation of CAS.

The resources

What are the locks of pessimism and optimism


Any mistakes in the article are welcome to correct, common progress!