Group Locking

  1. The Java language provides a single monitor per object of a given class, plus another for the class itself. It is tempting to use this monitor directly for all synchronization which needs to occur in a Java program.

  2. In a hierarchy of objects, some operations such as paint( ) will traverse the hierarchy from the top down. Others such as repaint( ) will traverse the hierarchy from the bottom up. If operations of both types need synchronization (and they often will), then deadlock can occur.

  3. The classical solution for deadlock is to ensure that locks are always acquired in a particular order. In this case, either the top-down or bottom-up traversals need to be made unsynchronized. This may not be practical.

  4. Another solution is to add a second monitor to each object using an explicit Lock object, and use one set for top-down and the other set for bottom-up traversal. This can be made to work, but is difficult and error prone.

  5. The solution used in IDVI is a vastly simplified one, but one which was certainly not obvious at first: use a single ReadWriteLock to control access to the entire hierarchy. As long as individual accesses are relatively fine-grained, this provides sufficient opportunity for multi-threading while reducing complexity and eliminating the possibility of deadlock.

    In general, consider using a single lock to control access to a large complicated data structure, instead of synchronizing access to each part of the data structure.