Defined:
Pessimistic lock (Pessimistic lock):
Every time you get the data, you will worry about the data is modified, so every time you get the data will be locked, to ensure that in their own use of the data will not be modified by others, using the completion of the data unlock. Because the data is locked, other threads that read and write to the data are waiting.
Optimistic lock (Optimistic lock):
Every time you get the data, you don't worry about the data being modified, so you don't lock it every time you get the data, but when you update the data, you need to decide if the data has been modified by someone else. If the data is modified by another thread, no data updates are made and data is updated if the data is not modified by another thread. Because the data is not locked, the data can be read and write by other threads. Applicable scenario:
Pessimistic lock: more suitable for write operations more frequent scenes, if a large number of read operations, each read will be added lock, which will increase the cost of a large number of locks, reducing the system throughput.
Optimistic lock: More suitable for reading operations more frequent scenes, if a large number of write operations, the likelihood of data conflict will increase, in order to ensure the consistency of data, the application layer needs to constantly regain data, which will increase the number of query operations, reducing the system throughput.
Summary: Both have advantages and disadvantages, read frequently use optimistic lock, write frequently use pessimistic lock.