Sobes.tech
Middle — Middle+

How can a pessimistic locking mechanism be implemented to ensure data integrity in a multithreaded environment?

sobes.tech AI

Answer from AI

Pessimistic locking assumes that when accessing data, it is locked so that other threads cannot modify it simultaneously, preventing race conditions and ensuring data integrity.

In Java, this can be implemented using synchronization or classes from java.util.concurrent.locks.

Example using ReentrantLock:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SharedResource {
    private final Lock lock = new ReentrantLock();
    private int data;

    public void updateData(int value) {
        lock.lock(); // lock the resource
        try {
            // critical section
            data = value;
            // additional operations
        } finally {
            lock.unlock(); // release the lock
        }
    }

    public int readData() {
        lock.lock();
        try {
            return data;
        } finally {
            lock.unlock();
        }
    }
}

Thus, while one thread holds the lock, other threads wait, preventing simultaneous data modification and ensuring their integrity.

How can a pessimistic locking mechanism be… - sobes.tech