Optimistic vs Pessimistic Locking Interview Questions and Answers
Master Optimistic vs Pessimistic Locking in JPA with interview questions covering @Version, LockModeType, concurrency control, deadlocks, performance, production scenarios, and best practices.
Introduction
In enterprise applications, multiple users often access and update the same database record concurrently. If concurrency is not handled properly, applications can suffer from lost updates, inconsistent data, race conditions, and deadlocks.
JPA provides two primary concurrency control mechanisms:
- Optimistic Locking – Detects conflicts during commit using a version column.
- Pessimistic Locking – Prevents conflicts by locking database rows immediately.
Choosing the correct strategy directly impacts performance, scalability, user experience, and database throughput.
Locking Overview
flowchart TD
A[Concurrent Transactions]
A --> B[Optimistic Locking]
A --> C[Pessimistic Locking]
B --> D[Version Check]
C --> E[Database Row Lock]
Q1. What is the difference between Optimistic and Pessimistic Locking?
Answer
Both mechanisms solve concurrent update problems but follow different strategies.
| Optimistic Locking | Pessimistic Locking |
|---|---|
| Assumes conflicts are rare | Assumes conflicts are frequent |
| No database lock initially | Locks row immediately |
Uses @Version |
Uses database locks |
| Better scalability | Lower scalability |
| Higher throughput | More waiting |
Can throw OptimisticLockException |
Can cause lock timeout or deadlock |
Q2. How does Optimistic Locking work?
Optimistic locking checks whether another transaction modified the entity before committing.
Entity
@Entity
public class Account {
@Id
private Long id;
@Version
private Integer version;
private Double balance;
}
Flow
sequenceDiagram
participant User1
participant User2
participant DB
User1->>DB: Read Version=1
User2->>DB: Read Version=1
User1->>DB: Update Version=2
DB-->>User1: Success
User2->>DB: Update Version=1
DB-->>User2: OptimisticLockException
Q3. How does Pessimistic Locking work?
Pessimistic locking immediately locks the row.
Other transactions must wait until the lock is released.
Example
Account account =
entityManager.find(
Account.class,
1L,
LockModeType.PESSIMISTIC_WRITE
);
Flow
flowchart LR
Transaction1 --> Lock
Lock --> Database
Transaction2 --> Waiting
Q4. What is @Version?
@Version enables optimistic locking by maintaining a version number.
@Version
private Long version;
Example
| Before Update | After Update |
|---|---|
| Version = 1 | Version = 2 |
Hibernate automatically increments the version during successful updates.
Q5. What are the available LockModeTypes?
| Lock Mode | Purpose |
|---|---|
| OPTIMISTIC | Version check |
| OPTIMISTIC_FORCE_INCREMENT | Version increment |
| PESSIMISTIC_READ | Shared lock |
| PESSIMISTIC_WRITE | Exclusive lock |
| PESSIMISTIC_FORCE_INCREMENT | Lock + version increment |
| NONE | No locking |
Example
entityManager.find(
Customer.class,
1L,
LockModeType.PESSIMISTIC_WRITE
);
Q6. Which locking strategy performs better?
Optimistic Locking
✔ Higher throughput
✔ Better scalability
✔ No database lock
✔ Less waiting
Pessimistic Locking
✔ Better for frequent conflicts
✔ Prevents simultaneous updates
✔ More blocking
✔ Higher database overhead
Comparison
flowchart LR
Optimistic --> Fast
Optimistic --> Scalable
Pessimistic --> Safe
Pessimistic --> Waiting
Q7. When should each strategy be used?
Use Optimistic Locking
- Banking profile updates
- User accounts
- Product management
- Employee management
- Reporting
Use Pessimistic Locking
- Money transfers
- Seat booking
- Stock trading
- Inventory deduction
- Payment processing
Q8. What are common problems?
Optimistic Locking
- OptimisticLockException
- Retry required
Pessimistic Locking
- Deadlocks
- Lock timeout
- Blocking
- Lower throughput
Diagram
flowchart LR
TransactionA --> Waiting
Waiting --> TransactionB
TransactionB --> WaitingA
Q9. Banking Example
Suppose two users withdraw money simultaneously.
Without locking
Balance = 1000
User1 Withdraw = 500
User2 Withdraw = 700
Incorrect Balance
With Optimistic Locking
Only one transaction succeeds.
Second transaction retries.
With Pessimistic Locking
Second transaction waits until first completes.
Q10. Best Practices
Prefer Optimistic Locking
Use
@Version
for most enterprise applications.
Keep Transactions Short
Avoid holding locks for long periods.
Retry OptimisticLockException
try{
// update
}
catch(OptimisticLockException ex){
// retry
}
Use Pessimistic Locking Carefully
Only for highly critical operations.
Monitor Deadlocks
Enable database monitoring for lock waits.
Feature Comparison
| Feature | Optimistic | Pessimistic |
|---|---|---|
| Database Lock | No | Yes |
| Version Column | Yes | Optional |
| Blocking | No | Yes |
| Deadlock Risk | Very Low | High |
| Throughput | High | Medium |
| Performance | Better | Lower |
| Conflict Handling | Exception | Waiting |
| Best For | Read-heavy systems | Write-heavy systems |
Common Interview Questions
- What is optimistic locking?
- What is pessimistic locking?
- Why do we use
@Version? - What is
OptimisticLockException? - What is
LockModeType? - Which locking strategy is faster?
- Which locking strategy is more scalable?
- What causes deadlocks?
- When should pessimistic locking be used?
- Which locking strategy do banks use?
Quick Revision
| Topic | Summary |
|---|---|
| Optimistic Locking | Uses version column |
| Pessimistic Locking | Uses database row lock |
| @Version | Enables optimistic locking |
| LockModeType | Defines lock strategy |
| Deadlock | Circular waiting |
| Lock Timeout | Waiting exceeds limit |
| Retry | Handle optimistic conflicts |
| Throughput | Optimistic is higher |
| Scalability | Optimistic is better |
| Banking | Use based on contention |
Execution Flow
sequenceDiagram
Application->>EntityManager: Read Entity
EntityManager->>Database: SELECT
Application->>EntityManager: Modify Entity
EntityManager->>Database: Version Check / Lock
Database-->>EntityManager: Success or Exception
EntityManager-->>Application: Commit / Retry
Key Takeaways
- Optimistic Locking detects concurrent updates using a
@Versionfield instead of locking rows immediately. - Pessimistic Locking locks database rows at the beginning of a transaction to prevent concurrent modifications.
- Optimistic locking provides better performance, scalability, and throughput for read-heavy applications.
- Pessimistic locking is appropriate for high-contention scenarios such as payments, inventory management, and seat reservations.
OptimisticLockExceptionindicates another transaction has already modified the same entity.LockModeTypedefines the locking behavior used by JPA during entity retrieval.- Keep transactions short to reduce lock contention and improve database performance.
- Implement retry logic when using optimistic locking in business-critical workflows.
- Use pessimistic locking only when the probability of concurrent conflicts is high.
- Selecting the correct locking strategy is essential for building reliable, scalable enterprise applications.