Reentrant locks and whether they work across different objects
Filed under Walmart
Free read 2 of 3A reentrant lock lets the thread that already holds it acquire it again without blocking; it tracks a hold count and is released when the count returns to zero. Java's synchronized and ReentrantLock are both reentrant.
The question
What are reentrant locks, and can they work with different objects?
Approach
A reentrant lock lets the thread that already holds it acquire it again without blocking; it tracks a hold count and is released when the count returns to zero. Java's synchronized and ReentrantLock are both reentrant.
Without reentrancy a synchronized method calling another synchronized method on the same object would deadlock itself.
Compared with synchronized it offers tryLock, timed and interruptible locking, optional fairness and multiple Conditions. Always unlock in a finally block.
A lock protects what you choose, not a specific object. One lock instance can guard several objects (coarse-grained), or each object can have its own lock (fine-grained). Threads using different lock instances do not exclude each other, so shared data needs the same lock. With multiple locks, use a consistent order to avoid deadlock.
Tips
- What they are testing: Understanding that exclusion depends on sharing the same lock instance.
- Common mistake: Assuming a lock instance automatically protects any object, or forgetting to unlock in finally.
Related Walmart questions
Collected from public candidate posts and coding forums. Updated Nov 2026.