I told Morgan Stanley interviewers that reentrantLock is basically same thing as Synchronized keyword. Basically same thing but with additional features:
- Feature: lockInterruptibly() is very useful if you need to cancel a “grabbing” thread.
- Feature: tryLock() is very useful. It can an optional timeout argument.
Above features all help us deal with deadlock:)
- Feature: Multiple condition variables on the same lock.
- Feature: lock fairness is configurable. A fair lock favors longest-waiting thread. Synchronized keyword is always unfair.
- — query operations —
- Feature: bool hasQueuedThread(targetThread) gives a best-effort answer whether targetThread is waiting for this lock
- Feature: Collection getQueuedThreads() gives a best-effort list of “grabbing” threads on this lock
- Feature: Collection getWaitingThreads (aConditionVar) gives a best-effort view of the given “waiting room”.
- Feature: int getHoldCount() basically gives the “net” re-entrancy count
- Feature: bool isHeldByCurrentThread()