Don’t Be Afraid to Use Optimistic Concurrency
Depending on your database engine, you might have the ability to choose between optimistic or pessimistic concurrency models. If your database supports pessimistic concurrency, you can enforce it through either database configuration or JDBC configuration.
The concurrency model you select determines whether you or the database engine is responsible for preventing dirty writes—that is, preventing one person from overwriting changes made by another based on old data from the database. Under optimistic concurrency, changes can be made to a row between the time it is read and the time updates are sent to the database. Without special logic in your application, systems that rely on optimistic concurrency run the risk of the following chain of events:
User A fetches a data record for a specific person from the database.
User B fetches the same data record.
User A changes a field in that data (e.g., the marital status of the person) and sends the update to the database.
User B changes another field in that data (e.g., the home phone number of the person) and sends the update to the database.
The consequence of this chain of events is an invalid marital status in the database. The status is no longer valid because User B overwrote the change in marital status of User A with the dirty data from its original read.
Pessimistic concurrency prevents dirty writes. How it prevents dirty writes depends on your database engine. Put succinctly, pessimistic ...