The previous blog describes what is thread synchronization, describes the use of synchronized, this blog summarizes pessimistic lock and optimistic lock.
Pessimistic lock, it assumes that as long as there is data access will create a conflict, when a thread reads data must be locked, other users can not operate until the lock is released.
Pessimistic locks are implemented using the data mechanism, where the SQL statement is added "for update" in the query, so that the entire transaction is locked and the next thread operation can be performed only after the end of the transaction execution. This prevents other processes from reading or modifying the data in the table
Select value from t_table_id where table_name=? for update
Optimistic lock, which assumes that there is no conflict when data is accessed, but checks whether the data integrity is violated when the transaction is committed, and whether the version number is consistent when updating.
For example, the data version in the database is 6, update commits version=6+1, use the version value (=7) compared with the database version+1 (=7), if it is equal, it can be updated, if not unequal it is possible that other programs have updated the record, so an error is returned. Optimistic locking is useful for applications that read from a database.
Optimistic locking is more suitable for less modification of tables, and pessimistic locking is more useful for data modification, which guarantees thread synchronization without generating dirty data.