Java Concurrency Interview

Locks, conditions and AQS question 43 of 180 mid

Can a thread deadlock against itself?

synchronized and ReentrantLock are reentrant, so recursion is fine there. StampedLock is not reentrant: asking for its write lock while already holding the write lock or a read lock parks the thread forever, because the owner it waits for is itself. A second read lock usually succeeds, since reads are shared, but it can still hang if a writer has queued in between.

The subtler case is lock upgrade. Holding a read lock and asking for the write lock waits for all readers to leave, including the caller, which never will. Downgrading is legal and supported: take the write lock, acquire the read lock while still holding it, then release the write lock.

Thread.currentThread().join() is a third way to hang forever, and appears in interviews as a trick question rather than as real code.

locks deadlock

Quiz yourself on Locks, conditions and AQS Suggest a correction