Optimistic Concurrency

Consider the following archetypical example. A user selects a widget to edit. The application displays details about the widget for editing. The user changes the widget’s attributes and submits the changes. This process involves two distinct transactions. The application obtains the widget for the user to edit in the first transaction. The application updates the widget in the database using a second transaction, committing the first user’s changes. Now, what if another user edited the same widget before the second transaction of the first user was committed. The second user’s changes are lost! This application behavior is often referred to as the last update/write wins policy. It’s also sometimes called the lost update problem. It’s likely that this behavior is not intentional since the changes are lost silently.

Why don’t transaction isolation levels help here? Transaction isolation levels apply only to concurrent transactions. In our case, we’re talking about distinct transactions that conflict with each other in terms of outcomes. If the application performed both operations within a single transaction, isolation levels could be used to ensure that two users working concurrently would not conflict with each other. But with the work broken down into two separate transactions for each user, the lost update problem is a possibility.

One simple and potentially elegant solution to this problem is optimistic concurrency. Before every update, you simply ensure ...

Get Java Enterprise in a Nutshell, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.