Java lock

‮tth‬ps://www.theitroad.com

In Java, a lock is an object used to enforce mutual exclusion, allowing only one thread to execute a critical section of code at a time. The java.util.concurrent.locks package provides several classes that can be used for this purpose.

The most commonly used lock is the ReentrantLock class. This lock provides the same basic behavior as the synchronized keyword, but it offers additional features, such as the ability to interrupt a waiting thread and the ability to attempt to acquire a lock without blocking.

Here's an example of how to use ReentrantLock to synchronize access to a shared resource:

import java.util.concurrent.locks.ReentrantLock;

public class SharedResource {
    private final ReentrantLock lock = new ReentrantLock();
    private int counter = 0;

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

    public int getCounter() {
        lock.lock();
        try {
            return counter;
        } finally {
            lock.unlock();
        }
    }
}

In this example, the SharedResource class has a ReentrantLock instance variable called lock. The increment() and getCounter() methods both acquire and release the lock using the lock() and unlock() methods, respectively.

It's important to always release the lock, either through normal program flow or in a finally block, to avoid deadlocks.

Locks provide more fine-grained control over thread synchronization than the synchronized keyword, but they also require more boilerplate code to use properly. It's important to use locks only when they're needed, and to always release them when they're no longer needed.