Sobes.tech
Junior — Middle
135

What is the purpose of the ReentrantLock class in Java and how does it compare to synchronized?

Companies where asked
Альфа-БанкАльфа-Банк

Answer from AI

sobes.tech AI

The ReentrantLock class in Java is used to control access to shared resources in a multithreaded environment, providing a lock mechanism with reentrant capability. This means that a thread that already holds the lock can acquire it again without deadlocking.

Advantages of ReentrantLock compared to the synchronized keyword:

  • Flexibility in lock management: you can explicitly acquire and release the lock, allowing for more complex synchronization scenarios.
  • Ability to interrupt waiting for the lock: the lockInterruptibly() method allows a thread to be interrupted while waiting for the lock.
  • Attempt to acquire the lock without waiting: the tryLock() method attempts to acquire the lock and immediately returns a result, without blocking the thread.
  • Support for conditions (Condition): ReentrantLock provides Condition objects for more fine-grained waiting and notification, unlike wait()/notify() in synchronized.

Example of using ReentrantLock:

import java.util.concurrent.locks.ReentrantLock;

public class Counter {
    private final ReentrantLock lock = new ReentrantLock();
    private int count = 0;

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

    public int getCount() {
        lock.lock();
        try {
            return count;
        } finally {
            lock.unlock();
        }
    }
}