Sobes.tech
Junior — Middle

Explain the principle of the optimistic locking method in managing concurrent data access.

sobes.tech AI

Answer from AI

Optimistic locking is an approach to managing concurrent access to data, where conflicts during simultaneous data modifications are assumed to be rare. Instead of locking resources in advance, the system allows multiple transactions to operate in parallel, and conflict checking is performed only when attempting to save changes.

Working principle:

  1. The transaction reads data and records its version or state.
  2. It makes necessary changes locally.
  3. When saving, it checks whether the data has changed since it was read (comparing the version).
  4. If the data has not changed, the changes are applied.
  5. If the data has changed, the transaction is rolled back or retried.

This approach can increase performance in systems with low contention by avoiding locking costs.

Example in Java using version:

class Data {
    private int value;
    private int version;

    public synchronized boolean update(int newValue, int oldVersion) {
        if (this.version == oldVersion) {
            this.value = newValue;
            this.version++;
            return true;
        }
        return false; // conflict
    }

    public synchronized int getVersion() {
        return version;
    }

    public synchronized int getValue() {
        return value;
    }
}

The transaction reads value and version, changes value, and attempts to update, checking the version."}]}]}