Sobes.tech
Senior

Tell about optimistic and pessimistic locking, when to apply them?

sobes.tech AI

Answer from AI

Optimistic and pessimistic locking are two approaches to managing concurrent access to data.

  • Pessimistic locking assumes that conflicts will be frequent, so the resource is locked during the operation to prevent others from modifying it. It is typically used in systems with high contention and critical data.

  • Optimistic locking assumes that conflicts are rare. The operation proceeds without locking, but before saving, it checks whether the resource has changed since it was read (for example, by version or timestamp). If it has changed, the operation is rolled back or retried.

When to apply:

  • Pessimistic locking is suitable for transactions with long execution times and high conflict probability, such as banking operations.

  • Optimistic locking is suitable for systems with low contention, where it is important not to lock resources, such as web applications with infrequent conflicts.

Example of optimistic locking in Kotlin using version:

data class Entity(var data: String, var version: Int)

fun updateEntity(entity: Entity, newData: String, currentVersion: Int): Boolean {
    if (entity.version != currentVersion) {
        // Conflict, version has changed
        return false
    }
    entity.data = newData
    entity.version += 1
    return true
}

Here, before updating, we check that the version has not changed; otherwise, we rollback the operation.

Tell about optimistic and pessimistic locking, when… - sobes.tech