Sobes.tech
Junior — Middle

Explain the principle of optimistic locking in concurrency control and its features.

sobes.tech AI

Answer from AI

Optimistic locking is an approach to managing concurrent access to data, where conflicts are assumed to be rare and not frequent.

How it works:

  • No lock is placed when reading data.
  • When attempting to write, the system checks whether the data has changed since it was read (for example, by comparing a version or checksum).
  • If the data has not changed, the write succeeds.
  • If the data has changed, the operation is rolled back or retried.

Features:

  • Suitable for systems with low contention, where locks are not needed constantly.
  • Improves performance by avoiding long locks.
  • Requires a mechanism to check the version or state of data (e.g., a version field in the database).

Example in Java (simplified):

class Entity {
    int version;
    String data;
}

// When updating, check the version
boolean update(Entity oldEntity, String newData) {
    Entity current = loadFromDb(oldEntity.id);
    if (current.version != oldEntity.version) {
        return false; // conflict
    }
    current.data = newData;
    current.version++;
    saveToDb(current);
    return true;
}

Thus, optimistic locking allows avoiding locks during operation but requires conflict handling during writing.

Explain the principle of optimistic locking in… - sobes.tech