Junior — Middle
Can you list different types of locking mechanisms used in multithreaded programming?
sobes.tech AI
Answer from AI
In multithreaded programming in Java, different locking mechanisms are used to synchronize access to shared resources:
- synchronized — an built-in locking mechanism that can be applied to methods or code blocks. It uses the object's monitor.
- ReentrantLock from the
java.util.concurrent.lockspackage — a more flexible lock with the ability to interrupt, timeout, and check its state. - ReadWriteLock — allows separating locks for reading and writing, which improves performance with a high number of read operations.
- Semaphore — limits the number of threads that can access a resource simultaneously.
- CountDownLatch and CyclicBarrier — for thread coordination, although these are not classic locks but synchronizers.
Example of using ReentrantLock:
import java.util.concurrent.locks.ReentrantLock;
ReentrantLock lock = new ReentrantLock();
lock.lock();
try {
// critical section
} finally {
lock.unlock();
}