ReentrantLock is a synchronization aid that allows threads to lock and unlock a specific resource. It belongs to the java.util.concurrent.locks package and provides more advanced locking mechanisms than the traditional synchronized block. With ReentrantLock, a thread can reacquire the lock that it already holds, which prevents deadlocks and improves concurrency in multi-threaded environments.
Here’s an example of how to use ReentrantLock:
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLockExample {
private final ReentrantLock lock = new ReentrantLock();
public void exampleMethod() {
lock.lock(); // Acquire the lock
try {
// Critical section
System.out.println("Lock is held by " + Thread.currentThread().getName());
// Perform some operations
} finally {
lock.unlock(); // Release the lock
}
}
}
public class Main {
public static void main(String[] args) {
ReentrantLockExample example = new ReentrantLockExample();
Thread thread1 = new Thread(example::exampleMethod);
Thread thread2 = new Thread(example::exampleMethod);
thread1.start();
thread2.start();
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?