Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

Share this Page URL

Chapter 10. Concurrency > Item 67: Avoid excessive synchronization - Pg. 265

ITEM 67: AVOID EXCESSIVE SYNCHRONIZATION 265 Item 67: Avoid excessive synchronization Item 66 warns of the dangers of insufficient synchronization. This item concerns the opposite problem. Depending on the situation, excessive synchronization can cause reduced performance, deadlock, or even nondeterministic behavior. To avoid liveness and safety failures, never cede control to the client within a synchronized method or block. In other words, inside a synchronized region, do not invoke a method that is designed to be overridden, or one provided by a client in the form of a function object (Item 21). From the perspective of the class with the synchronized region, such methods are alien. The class has no knowledge of what the method does and has no control over it. Depending on what an alien method does, calling it from a synchronized region can cause excep- tions, deadlocks, or data corruption. To make this concrete, consider the following class, which implements an observable set wrapper. It allows clients to subscribe to notifications when ele- ments are added to the set. This is the Observer pattern [Gamma95, p. 293]. For brevity's sake, the class does not provide notifications when elements are removed from the set, but it would be a simple matter to provide them. This class is imple-