Concurrency and Locking with JPA: Everything You Need to Know

Swathi Prasad
3 min readJun 10, 2019

Imagine you have a system used by multiple users, where each user is trying to modify the same entity concurrently. How do you ensure that the underlying data’s integrity is preserved when accessed concurrently?

The persistence providers offer locking strategy to manage concurrency. There are two types of locking: Optimistic locking and Pessimistic locking. Before we deep dive into locking strategy, let us understand a little bit about ACID transactions.

ACID (Atomicity, Consistency, Isolation, Durability) transactions ensure that a database transaction is completed in a timely manner. The relational databases such as MySQL, PostgreSQL, SQL server and Oracle are ACID compliant.

A database transaction can be broken down into multiple components. ACID compliant databases ensure that a transaction is persisted and committed, only when all the components of a transaction are succeeded. If any one of the components fail, the transaction will be rolled back and no change will be made.

In case of multiple transactions, we need to define locking strategy to make sure that underlying data’s integrity is preserved.

Let’s look at each locking strategy in this article.

Optimistic Locking

--

--

Swathi Prasad

Software architect and developer living in Germany. Sharing my opinion and what I learn.