JPA Locking Interview Questions and Answers

Master JPA Locking with interview questions covering optimistic locking, pessimistic locking, lock modes, @Version, deadlocks, transaction isolation, and production best practices.


JPA Locking Interview Questions and Answers

Introduction

In enterprise applications, multiple users may update the same database record simultaneously. Without proper locking mechanisms, this can lead to lost updates, inconsistent data, dirty reads, and race conditions.

JPA provides Optimistic Locking and Pessimistic Locking to ensure data consistency during concurrent transactions.

Locking is commonly used in banking, e-commerce, airline reservation systems, inventory management, and financial applications where data integrity is critical.


JPA Locking Architecture

flowchart LR

User1 --> Transaction1
User2 --> Transaction2

Transaction1 --> JPA

Transaction2 --> JPA

JPA --> Database

Q1. What is Locking in JPA?

Answer

Locking is a mechanism that prevents multiple transactions from corrupting the same data simultaneously.

Without locking

User A reads Balance = 1000

User B reads Balance = 1000

User A withdraws 500

User B withdraws 700

Final Balance = 300 ❌

Correct balance should be

1000 - 500 -700 = -200

Locking prevents such concurrency issues.

Benefits

  • Prevents lost updates
  • Maintains consistency
  • Protects concurrent transactions
  • Ensures data integrity

Q2. What are the types of Locking?

JPA provides two locking strategies.

Lock Type Description
Optimistic Locking Detect conflicts during commit
Pessimistic Locking Prevent conflicts immediately

Diagram

flowchart TD

Locking --> Optimistic

Locking --> Pessimistic

Q3. What is Optimistic Locking?

Answer

Optimistic locking assumes conflicts are rare.

Instead of locking rows immediately, JPA checks whether another transaction modified the row before committing.

It uses the @Version column.

Entity

@Entity
public class Account{

@Id
private Long id;

@Version
private Long version;

private Double balance;

}

Flow

sequenceDiagram
User1->>DB: Read Version=1
User2->>DB: Read Version=1
User1->>DB: Update Version=2
User2->>DB: Update Version=1
DB-->>User2: OptimisticLockException

Advantages

  • Better scalability
  • No database locks
  • Higher throughput

Q4. What is Pessimistic Locking?

Answer

Pessimistic locking locks the database row immediately.

Other transactions must wait.

Example

Account account =
entityManager.find(
Account.class,
1L,
LockModeType.PESSIMISTIC_WRITE
);

Diagram

flowchart LR

Transaction1 --> LockRow["Lock Row"]

Transaction2 --> Waiting

LockRow["Lock Row"] --> Database

Advantages

  • Prevents conflicts completely
  • Suitable for high-contention systems

Disadvantages

  • Lower performance
  • Can cause deadlocks

Q5. What are LockModeTypes?

Lock Mode Description
OPTIMISTIC Version check
OPTIMISTIC_FORCE_INCREMENT Increments version
PESSIMISTIC_READ Shared lock
PESSIMISTIC_WRITE Exclusive lock
PESSIMISTIC_FORCE_INCREMENT Exclusive + version increment
NONE No lock

Example

entityManager.find(
Account.class,
1L,
LockModeType.OPTIMISTIC
);

Q6. What is @Version?

Answer

@Version enables optimistic locking.

Every successful update increments the version.

Example

@Version
private Integer version;

Database

ID Balance Version
1 1000 1

After update

ID Balance Version
1 900 2

If another transaction still has version 1, Hibernate throws

OptimisticLockException

Q7. When should Optimistic Locking be used?

Use optimistic locking when

  • Reads are more frequent than writes
  • Conflicts are rare
  • High scalability is required
  • Large number of concurrent users

Examples

  • Online banking
  • Shopping websites
  • User profiles
  • Reporting systems

Q8. When should Pessimistic Locking be used?

Use pessimistic locking when

  • Conflicts are frequent
  • Financial transactions
  • Seat reservations
  • Inventory updates
  • Stock trading

Example

entityManager.find(
Account.class,
1L,
LockModeType.PESSIMISTIC_WRITE
);

Q9. What are common locking problems?

Lost Update

Two users overwrite each other's changes.

Deadlock

Transaction A waits for B.

Transaction B waits for A.

Lock Timeout

Transaction waits too long.

Blocking

Long-running transactions block others.

Diagram

flowchart LR

TransactionA --> Waiting

Waiting --> TransactionB

TransactionB --> WaitingA

Q10. Locking Best Practices

Prefer Optimistic Locking

Use @Version whenever possible.


Keep Transactions Short

Long transactions increase lock duration.


Avoid Unnecessary Pessimistic Locks

Database locking reduces throughput.


Retry OptimisticLockException

Typical approach

try{

// update

}
catch(OptimisticLockException ex){

// retry

}

Banking Example

flowchart TD

Customer --> Account

Account --> Withdraw

Withdraw --> OptimisticLock["Optimistic Lock"]

OptimisticLock["Optimistic Lock"] --> Database

Only one successful update increments the version.


Common Interview Questions

  • What is locking in JPA?
  • Difference between optimistic and pessimistic locking?
  • What is @Version?
  • What causes OptimisticLockException?
  • What are LockModeTypes?
  • What is a deadlock?
  • What is lock timeout?
  • When should pessimistic locking be used?
  • How does Hibernate implement optimistic locking?
  • Which locking strategy is better?

Quick Revision

Topic Description
Locking Prevents concurrent data corruption
Optimistic Locking Uses version column
Pessimistic Locking Locks database row
@Version Version control
LockModeType Lock strategy
Deadlock Circular waiting
Lost Update Overwritten changes
Lock Timeout Wait exceeds limit
Retry Handle optimistic conflicts
Best Practice Prefer optimistic locking

Locking Flow

sequenceDiagram
Application->>EntityManager: Read Entity
EntityManager->>Database: SELECT
Application->>EntityManager: Modify Entity
EntityManager->>Database: UPDATE
Database-->>EntityManager: Version Check
EntityManager-->>Application: Success / Exception

Key Takeaways

  • JPA locking ensures data consistency during concurrent transactions.
  • JPA supports Optimistic Locking and Pessimistic Locking.
  • Optimistic Locking uses the @Version field to detect concurrent modifications.
  • Pessimistic Locking acquires database locks immediately using LockModeType.
  • OptimisticLockException occurs when another transaction updates the same row before the current transaction commits.
  • Use Optimistic Locking for applications with many reads and fewer write conflicts.
  • Use Pessimistic Locking for high-contention scenarios like banking, ticket booking, and inventory management.
  • Keep transactions short to reduce lock contention and improve scalability.
  • Handle optimistic locking failures with a retry mechanism where appropriate.
  • Understanding JPA locking is essential for building reliable, high-concurrency enterprise applications.