Sobes.tech
Junior — Middle

Can you explain the concept of pessimistic locking and what it entails?

sobes.tech AI

Answer from AI

Pessimistic locking is an approach to managing concurrent access to data, where a resource is locked immediately upon an attempt to modify or read it, to prevent conflicts and data inconsistency. The idea is that the system anticipates potential conflicts and preemptively locks data, preventing other transactions from modifying or reading it until the lock is released.

In Java, this is often implemented using synchronization (synchronized), ReentrantLock, or other locking mechanisms. For example, if multiple threads try to modify the same object, pessimistic locking ensures that only one thread can do so at a time, while others wait.

Example with ReentrantLock:

import java.util.concurrent.locks.ReentrantLock;

public class Counter {
    private int count = 0;
    private final ReentrantLock lock = new ReentrantLock();

    public void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }

    public int getCount() {
        return count;
    }
}

Here, lock.lock() locks access to the resource until the current thread finishes working with it and calls lock.unlock().