HuntExams Academy logo
JavaAdvanced#concurrency

What is the difference between ReentrantLock and synchronized?

Answer

ReentrantLock (java.util.concurrent.locks) offers advanced features like tryLock with timeout, interruptible lock acquisition, and fairness policies, whereas synchronized is simpler but less flexible and always blocks indefinitely.

Example

ReentrantLock lock = new ReentrantLock();
if (lock.tryLock(1, TimeUnit.SECONDS)) {
  try { /* critical section */ } finally { lock.unlock(); }
}

Related Interview Questions

1
JavaAdvanced#concurrency#java8

What is a CompletableFuture and how does it improve async programming?

Open
2
JavaIntermediate#concurrency

What are the different thread pool types provided by Executors?

Open
3
JavaAdvanced#concurrency

What is thread starvation?

Open