Sobes.tech
Junior — Middle

Can you explain the principle of pessimistic locking and how it differs from other locking strategies?

sobes.tech AI

Answer from AI

Pessimistic locking is a concurrency control strategy where a resource is locked immediately upon access to prevent conflicts. For example, when a thread begins writing to a database, it places a lock, preventing other threads from reading or modifying the data until the lock is released.

The difference from optimistic locking is that optimistic locking assumes conflicts are rare and does not lock the resource in advance; instead, it checks data integrity only when saving changes. If a conflict is detected, the operation is rolled back or retried.

An example in Java using synchronized for pessimistic locking:

public class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }
}

Here, the increment method is locked for other threads until the current thread completes the operation.

Can you explain the principle of pessimistic locking… - sobes.tech