Sobes.tech
Junior — Middle

Can you explain the concept of optimistic locking and how it works in database management systems?

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. In database management systems, it works as follows:

  1. When a transaction reads data, it does not lock it.
  2. When attempting to write, the transaction checks whether the data has changed since it was read (for example, by comparing a version or checksum).
  3. If the data has not changed, the write succeeds.
  4. If the data has been modified by another transaction, the current operation is interrupted or retried.

This differs from pessimistic locking, where data is locked immediately upon reading or writing to prevent conflicts.

Example in Java using version for optimistic locking:

class Entity {
    private int version;
    private String data;

    public synchronized void update(String newData, int expectedVersion) throws Exception {
        if (this.version != expectedVersion) {
            throw new Exception("Data has been modified by another process");
        }
        this.data = newData;
        this.version++;
    }

    public synchronized int getVersion() {
        return version;
    }

    public synchronized String getData() {
        return data;
    }
}

Here, the version is used to check whether the data has changed since the last read.

Can you explain the concept of optimistic locking and… - sobes.tech