Sobes.tech
Junior — Middle

What is the difference between using ReentrantLock and the built-in synchronized keyword in Java?

sobes.tech AI

Answer from AI

ReentrantLock and synchronized — both are used for thread synchronization in Java, but they have several differences:

  • Flexibility: ReentrantLock provides additional features such as attempting to acquire the lock with a timeout (tryLock()), interrupting a thread waiting for a lock (lockInterruptibly()), and checking if the lock is held.

  • Performance: In some cases, ReentrantLock can be more efficient, especially under high contention, but this depends on the JVM implementation.

  • Lock management: synchronized automatically releases the lock when exiting the code block, whereas with ReentrantLock, you need to explicitly call unlock(), which requires careful handling to avoid deadlocks.

  • Fairness: ReentrantLock can be created with a fairness parameter, which guarantees that locks are granted to threads in the order of their requests, something that cannot be done with synchronized.

Example of using ReentrantLock:

import java.util.concurrent.locks.ReentrantLock;

ReentrantLock lock = new ReentrantLock();

lock.lock();
try {
    // critical section
} finally {
    lock.unlock();
}
What is the difference between using ReentrantLock… - sobes.tech