代码改变世界

Effective Java 70 Document thread safety

2014-05-04 08:54  小郝(Kaibo Hao)  阅读(505)  评论(0编辑  收藏  举报

Principle

  1. The presence of the synchronized modifier in a method declaration is an implementation detail, not a part of its exported API.
  2. To enable safe concurrent use, a class must clearly document what level of thread safety it supports.

    Immutable

    • immutable —Instances of this class appear constant. No external synchronization is necessary. Examples include String , Long, and BigInteger (Item 15).

    ThreadSafe

    • unconditionally thread-safe —Instances of this class are mutable, but the class has sufficient internal synchronization that its instances can be used concurrently without the need for any external synchronization. Examples include Random and ConcurrentHashMap.

    • conditionally thread-safe —Like unconditionally thread-safe, except that some methods require external synchronization for safe concurrent use. Examples include the collections returned by the Collections.synchronized wrappers, whose iterators require external synchronization.   

    Note

    If an object represents a view on some other object, the client generally must synchronize on the backing object, so as to prevent its direct modification. For example, the documentation for Collections.synchronizedMap says this:

    It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views:

    Map<K, V> m = Collections.synchronizedMap(new HashMap<K, V>());

    ...

    Set<K> s = m.keySet(); // Needn't be in synchronized block

    ...

    synchronized(m) { // Synchronizing on m, not s!

    for (K key : s)

    key.f();

    }   

    NotThreadSafe

    • not thread-safe—Instances of this class are mutable. To use them concurrently, clients must surround each method invocation (or invocation sequence) with external synchronization of the clients' choosing . Examples include the general-purpose collection implementations, such as ArrayList and HashMap.

    • thread-hostile— This class is not safe for concurrent use even if all method invocations are surrounded by external synchronization. Thread hostility usually results from modifying static data without synchronization. No one writes a thread-hostile class on purpose; such classes result from the failure to consider concurrency. Luckily, there are very few thread-hostile classes or methods in the Java libraries. The System.runFinalizersOnExit method is thread-hostile and has been deprecated.   

    The description of a class's thread safety generally belongs in its documentation comment, but methods with special thread safety properties should describe these properties in their own documentation comments.   

    It is not necessary to document the immutability of enum types. Unless it is obvious from the return type, static factories must document the thread safety of the returned object, as demonstrated by Collections.synchronizedMap (above).   

    Private lock object idiom

  3. preventdenial-of-service attack by avoiding holding publicly accessible lock from the client.
  4. Particularly well-suited to classes designed for inheritance.   

    // Private lock object idiom - thwarts denial-of-service attack

    private final Object lock = new Object();

    public void foo() {

    synchronized(lock) {

    ...

    }

    }   

    Summary

    Every class should clearly document its thread safety properties with a carefully worded prose description or a thread safety annotation. The synchronized modifier plays no part in this documentation. Conditionally thread-safe classes must document which method invocation sequences require external synchronization, and which lock to acquire when executing these sequences. If you write an unconditionally thread-safe class, consider using a private lock object in place of synchronized methods. This protects you against synchronization interference by clients and subclasses and gives you the flexibility to adopt a more sophisticated approach to concurrency control in a later release.