Item 67: Avoid excessive synchronization

1.  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. 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 exceptions, deadlocks, or data corruption. It is usually not too hard to fix this sort of problem by moving alien method invocations out of synchronized blocks.

 

2.  CopyOnWriteArrayList is a variant of ArrayList in which all write operations are implemented by making a fresh copy of the entire underlying array. Because the internal array is never modified, iteration requires no locking and is very fast.

 

3.  As a rule, you should do as little work as possible inside synchronized regions. Obtain the lock, examine the shared data, transform it as necessary, and drop the lock. If you must perform some time-consuming activity, find a way to move the activity out of the synchronized region.

 

4.  In a multicore world, the real cost of excessive synchronization is not the CPU time spent obtaining locks; it is the lost opportunities for parallelism and the delays imposed by the need to ensure that every core has a consistent view of memory. Another hidden cost of oversynchronization is that it can limit the VM’s ability to optimize code execution.

 

5.  You should make a mutable class thread-safe if it is intended for concurrent use and you can achieve significantly higher concurrency by synchronizing internally than you could by locking the entire object externally. Otherwise, don’t synchronize internally. Let the client synchronize externally where it is appropriate. When in doubt, do not synchronize your class, but document that it is not thread-safe. 

 

6.  If a method modifies a static field, you must synchronize access to this field, even if the method is typically used only by a single thread.

 

你可能感兴趣的:(thread-safe,alien method)