Optimistic lock, pessimistic lock, detailed explanation of distributed lock

In a multi-threaded concurrent environment, in order to ensure the consistency and correctness of data, it is necessary to use the lock mechanism to control the concurrency of shared resources. Common locks include optimistic locks, pessimistic locks, and distributed locks. The textual explanation and code explanation of these three locks will be given below.

Optimistic lock:

Optimistic locking is an optimistic idea. It believes that in most cases, concurrent access to data will not conflict, so there is no need to lock, but to judge by comparing version numbers or timestamps when updating data. Whether a conflict occurs. If a conflict occurs, a rollback or retry is required.

Code example for optimistic locking:

public class Account {
    
    
    private int id;
    private String name;
    private double balance;
    private int version;

    // getter and setter methods

    public void updateBalance(double amount) {
    
    
        // 通过比较版本号判断是否发生冲突
        while (true) {
    
    
            int oldVersion = version;
            double newBalance = balance + amount;
            // 模拟业务逻辑
            try {
    
    
                Thread.sleep(1000);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
            if (oldVersion == version) {
    
    
                balance = newBalance;
                version++;
                break;
            }
        }
    }
}

In the above code, it is judged whether there is a conflict by comparing the version numbers. If there is no conflict, update the data, otherwise try again.

Pessimistic lock:

Pessimistic locking is a pessimistic idea. It is believed that in concurrent access, data conflicts are very common. Therefore, it is necessary to lock when accessing data to prevent other threads from modifying data at the same time and ensure data consistency.

Code example for pessimistic locking:

public class Account {
    
    
    private int id;
    private String name;
    private double balance;

    // getter and setter methods

    public synchronized void updateBalance(double amount) {
    
    
        // 模拟业务逻辑
        try {
    
    
            Thread.sleep(1000);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        balance += amount;
    }
}

In the above code, use the synchronized keyword to modify the updateBalance method to ensure that only one thread can modify the data when accessing the data.

Distributed lock:

Distributed lock is a lock mechanism used in distributed systems to ensure that access to shared resources is atomic in a distributed environment. Distributed locks can be implemented using various technologies, such as database-based, cache-based, ZooKeeper-based, etc.

Code example for implementing distributed locks based on ZooKeeper:

public class DistributedLock {
    
    
    private CuratorFramework client;
    private InterProcessMutex lock;
    private String lockPath;

    public DistributedLock(String zkServers, String lockPath) {
    
    
        client = CuratorFrameworkFactory.newClient(zkServers, new RetryNTimes(10, 5000));
        client.start();
        this.lockPath = lockPath;
        lock = new InterProcessMutex(client, lockPath);
    }

    public void lock() throws Exception {
    
    
        lock.acquire();
    }

    public void unlock() throws Exception {
    
    
        lock.release();
    }
}

In the above code, ZooKeeper's InterProcessMutex is used to implement distributed locks to ensure that access to shared resources is atomic in a distributed environment.

It should be noted that when using the lock mechanism, problems such as deadlock and starvation need to be avoided, and issues such as lock granularity and lock efficiency also need to be considered. In practical applications, it is necessary to select the appropriate locking mechanism according to the specific situation to ensure the performance and reliability of the system.

Guess you like

Origin blog.csdn.net/weixin_65837469/article/details/131138181