Java Monitor

From APIDesign

Revision as of 07:15, 11 February 2009 by JaroslavTulach (Talk | contribs)
(diff) ←Older revision | Current revision (diff) | Newer revision→ (diff)
Jump to: navigation, search

The Java synchronization model with all synchronized, notify and wait its is commonly thought of as an example of monitors. However with closer look one finds out that it is far different to the model used in Concurrent Pascal. It is not that robust, it is not well enough integrated to the language and sort of feels like an assembly language with synchronization primitives than high-level abstraction provided by real monitor. However, it has yet another hidden flaw, kind of example of CopyBasedDesign problem: the Java Monitors implant the monitor into object oriented language, in an object oriented style and that does not work.

Imagine there is an Cache support class in some API:

// TBD

Its synchronization is sufficiently well designed. It never calls foreign code while holding own lock, which is one of necessary Deadlock Conditions. As such one would expect that there is no way to deadlock on the Caches lock. However that would be false assumption. Simple call like:

// TBD

can lead to deadlock. Moreover this all is achievable using the best Java synchronization practices. Just imagine there is a subclass of the Cache class which defines few properties and for better or worse guards them as Java Monitor:

// TBD

This code is not bulletproof. It notifies its listeners while holding own lock and as such this can lead to deadlocks. However it is common that people do these sort of mistakes when using an API. The API shall be ready to handle clueless clients. It is acceptable to let the clients of an API deadlock on their own locks, yet there is no reason to block the API itself. Yet this is the case:

// TBD

Simple call to get("123") deadlocks. Why? Because the Java Monitors implant the monitor concept into object oriented world and in the process of doing that break the most fundamental assumption: the monitor shall be encapsulated. One shall always define all internal data structures and operations working on them in one monitor.

// TBD

Personal tools
buy