SoFunction
Updated on 2025-04-24

Detailed process of Java optimistic locking to prevent data conflicts

1. The basic principle of optimistic locking

Optimistic locking assumes that data conflicts are uncommon in concurrent environments, so locks are not immediately acquired when operating on data. Instead, it checks whether the data is modified by other transactions when updating it. If the data is not modified, the update is successful; otherwise, the update fails and retry.

2. How to implement optimistic locks

(I) Version number mechanism

Add a version number field to the database table, and the version number will increment each time the data is updated. During the update operation, it checks whether the current version number is the same as the version number in the database. If consistent, the update succeeds; otherwise, the update fails.

import ;
import ;
import ;

@Entity
public class Account {
    @Id
    private Long id;
    private Double balance;
    @Version
    private Integer version;

    // Getters and Setters
}

(II) Time stamp mechanism

Add a timestamp field to the database table, and each time the data is updated, the timestamp is updated to the current time. During the update operation, it is checked whether the current timestamp is consistent with the timestamp in the database. If consistent, the update succeeds; otherwise, the update fails.

import ;
import ;
import ;
import ;
import ;

@Entity
public class Account {
    @Id
    private Long id;
    private Double balance;
    @Temporal()
    private Date lastModified;

    // Getters and Setters
}

3. Optimistic lock usage scenarios

Optimistic locks are suitable for scenarios where more reads and less writes, such as content management systems, historical data query, etc. In these scenarios, the data read operations are much more than the write operations, and optimistic locking can reduce the lock competition in the database and improve concurrency performance.

4. Summary

Optimistic locking uses the version number or timestamp mechanism to check whether the data is modified by other transactions when updating the data, thereby effectively preventing data conflicts. It is suitable for scenarios where more reads and less writes, and can improve the concurrency performance of the system. I hope the examples and explanations of this article will be helpful to you. If you have any questions when using optimistic locks, please feel free to communicate and discuss!

Expansion: Java Optimistic Locking Principles and Practical Guide

1. What is optimistic lock?

Optimistic locking is a concurrent control strategy, and its core idea is:Assuming that the data will not be modified by other transactions when updated. Therefore, under the optimistic lock mechanism, we do not need to exclusively lock shared resources like pessimistic locks (such assynchronizedorReentrantLock). Instead, we check if there is a conflict when submitting the update. If there is no conflict, the commit is successful; if there is a conflict, the rollback operation or retry.

In contrast,Pessimistic lockAssume that the data may be modified by other transactions at any time, so the locking mechanism needs to exclusive resources to avoid concurrency problems.

2. The core implementation method of optimistic lock

In Java, the implementation of optimistic locks usually relies on the following techniques:

1. Database-level version control

Databases are one of the most common application scenarios for optimistic locking. For example, in MySQLInnoDBIn the storage engine, it can be passedversion columns(version column) to achieve optimistic concurrency control.

Example: Use version number to achieve optimistic lock

public class User {
    private Long id;
    private String username;
    private Integer version; // Version number field}
 
// Check the version number when updating user informationString sql = "UPDATE user SET username=?, version=version+1 WHERE id=? AND version=?";
int affectedRows = (sql, newUsername, userId, currentVersion);
if (affectedRows == 0) {
    throw new OptimisticLockException("The data has been modified, please reload the latest version.");
}

2. CAS (Compare-And-Swap) algorithm

CAS is a lock-free algorithm that is widely used in JavaAtomicIn the class. Its core idea is:Compare whether the current value is consistent with the expected value, and if it is consistent, perform an update operation.

Example: UseAtomicIntegerAchieve optimistic lock

import ;
 
public class OptimisticCounter {
    private AtomicInteger count = new AtomicInteger(0);
 
    public int increment() {
        int current;
        int next;
        do {
            current = ();
            next = current + 1;
        } while (!(current, next));
        return next;
    }
}

3. StampedLock in Java

StampedLock is a new lock mechanism introduced by Java 8, which combines the characteristics of optimistic lock and pessimistic lock. Through the tryOptimisticRead() and tryOptimisticWrite() methods, we can achieve efficient and optimistic concurrency control.

Example: Use StampedLock to achieve optimistic reading

import ;
 
public class StampedLockExample {
    private final StampedLock lock = new StampedLock();
    private long version; // Version number    private int data;
 
    public int read() {
        long stamp = ();
        int value = data;
        if (!(stamp)) {
            // Optimistic reading fails, try to add pessimistic lock            stamp = ();
            try {
                value = data;
            } finally {
                (stamp);
            }
        }
        return value;
    }
}

3. Advantages and disadvantages of optimistic lock

Advantages

  1. Low blockage: Optimistic locking reduces blockage between threads and improves the concurrency performance of the system.
  2. High throughput: In scenarios with fewer data conflicts, optimistic locks perform better than pessimistic locks.

Disadvantages

  1. ABA Question: Since optimistic locks only check version number or changes in specific values, it may cause ABA (Atomicity, Consistency, Availability) problems. For example, in a CAS operation, if a variable is changed back to its original value, CAS will not be able to detect this change.
  2. Performance fluctuations: In high concurrency scenarios, frequent conflicts will lead to an increase in the number of retry times, which will affect performance.

4. Optimistic lock application scenarios

Optimistic locks are suitable for the following scenarios:

  1. Systems with more reading and less writing: In this scenario, optimistic locking can significantly reduce lock competition and improve throughput.
  2. Scenarios with low probability of data conflict: For example, when updating a counter in a distributed cache, if the probability of multiple clients modifying at the same time is very low, you can choose optimistic lock.

Instead, optimism locks should be avoided in the following scenarios:

  1. High concurrent write operation: In this case, frequent conflicts can lead to severe performance degradation.
  2. Scenarios that require strong consistency guarantee: For example, in a bank transfer system, it is necessary to ensure that each update can be completed atomically.

The above is the detailed content of the detailed process of Java optimistic lock preventing data conflict. For more information about Java optimistic lock preventing data conflict, please pay attention to my other related articles!