In this first entry on Java's top 10 concurrency problems, blogger Peter Veentjer walks us through the Nested Monitor Lockout scenario.
This problem is called: 'nested monitor lockout'. Composing larger structures (e.g. kitchens) from smaller structures (e.g. fridges) is a technique all object oriented developers use on a daily basis (dependency injection, object composition, decorators, template methods, proxies, strategies, etc). But as soon as these structures block and are wrapped within other concurrent structures, you can get in serious liveness problems. So one of the first things I look at is if synchronized structures are wrapped in other synchronized structures and possible do blocking calls (if you are lucky, the methods throw an InterruptedException). But this can be a very challenging task if the concurrent code isn't localized but scattered all over the place or when the InterruptedExceptions aren't handled correctly. Maybe in the future techniques like STM (Software Transactional Memory) can help us, but for the moment we need to keep paying extra attention to concurrency control. It is very easy to cause liveness problems with conditions (aka condition variables) but it is not just the direct usage that can cause problems, also techniques like object composition can be quite dangerous. A condition is a very low level synchronization structure that makes it possible for threads to wait for an event to occur, e.g. the return of a license in a semaphore or the placement of an item on a queue. So a lot of higher order concurrency structures are build on top of conditions and this makes them one of the most fundamental concurrency abstractions. The big question is: how can the usage of a condition cause a deadlock? When a thread is going to wait for a notification, it blocks, it is added to a wait-set (a set of blocking threads that wait for that condition) and the associated lock is released. Releasing and reacquiring the lock is done behind the screens and luckily is not a task developers need to deal with. But if the waiting thread never receives the notification it is waiting for, the thread won't wake-up and therefore is in a deadlock.
Read Peter's complete post on Nested Monitor Lockout http://blog.xebia.com/2008/01/22/ejcp-top-10-nested-monitor-lockout/