Defined:
Pessimistic lock (Pessimistic lock):
Every time you get the data, you worry about the data being modified, so lock it every time you get the data, make sure the data will not be changed by others when you use it, and unlock the data when you're done. Because the data is locked, other threads that read and write to that data during the period will wait.
Optimistic lock (Optimistic lock):
Every time you get data, you don't worry about the data being modified, so you don't lock it up every time you get the data, but when you update the data, you need to know if the data has been modified by someone else. If the data is modified by another thread, the data is not updated and the data is updated if the data is not modified by another thread. Because the data is not locked, the data can be read and written by other threads.
Applicable scenarios:
Pessimistic lock: more suitable for writing more frequent scenes, if there is a large number of read operations, each time the reading will be locked, which will increase the cost of a large number of locks, reducing the system's throughput.
Optimistic lock: More suitable for reading more frequent scenes, if there is a large number of write operations, the likelihood of data conflicts 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's throughput.
Summary: Both have advantages and disadvantages, read frequently use optimistic lock, write frequent use pessimistic lock.
Java programming: The difference between pessimistic lock and optimistic lock and the usage scene