## Chapter 11. Concurrency(并發)
### Item 82: Document thread safety(文檔應包含線程安全屬性)
How a class behaves when its methods are used concurrently is an important part of its contract with its clients. If you fail to document this aspect of a class’s behavior, its users will be forced to make assumptions. If these assumptions are wrong, the resulting program may perform insufficient synchronization (Item 78) or excessive synchronization (Item 79). In either case, serious errors may result.
類在其方法并發使用時的行為是其與客戶端約定的重要組成部分。如果你沒有記錄類在這一方面的行為,那么它的用戶將被迫做出假設。如果這些假設是錯誤的,生成的程序可能缺少足夠的同步([Item-78](/Chapter-11/Chapter-11-Item-78-Synchronize-access-to-shared-mutable-data.md))或過度的同步([Item-79](/Chapter-11/Chapter-11-Item-79-Avoid-excessive-synchronization.md))。無論哪種情況,都可能導致嚴重的錯誤。
You may hear it said that you can tell if a method is thread-safe by looking for the synchronized modifier in its documentation. This is wrong on several counts. In normal operation, Javadoc does not include the synchronized modifier in its output, and with good reason. **The presence of the synchronized modifier in a method declaration is an implementation detail, not a part of its API.** It does not reliably indicate that a method is thread-safe.
你可能聽說過,可以通過在方法的文檔中查找 synchronized 修飾符來判斷方法是否線程安全。這個觀點有好些方面是錯誤的。在正常操作中,Javadoc 的輸出中沒有包含同步修飾符,這是有原因的。方法聲明中 synchronized 修飾符的存在是實現細節,而不是其 API 的一部分。**它不能可靠地表明方法是線程安全的。**
Moreover, the claim that the presence of the synchronized modifier is sufficient to document thread safety embodies the misconception that thread safety is an all-or-nothing property. In fact, there are several levels of thread safety. **To enable safe concurrent use, a class must clearly document what level of thread safety it supports.** The following list summarizes levels of thread safety. It is not exhaustive but covers the common cases:
此外,聲稱 synchronized 修飾符的存在就足以記錄線程安全性,這個觀點是對線程安全性屬性的誤解,認為要么全有要么全無。實際上,線程安全有幾個級別。**要啟用安全的并發使用,類必須清楚地記錄它支持的線程安全級別。** 下面的列表總結了線程安全級別。它并非詳盡無遺,但涵蓋以下常見情況:
- **Immutable** —Instances of this class appear constant. No external synchronization is necessary. Examples include String, Long, and BigInteger (Item 17).
不可變的。這個類的實例看起來是常量。不需要外部同步。示例包括 String、Long 和 BigInteger([Item-17](/Chapter-4/Chapter-4-Item-17-Minimize-mutability.md))。
- **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 AtomicLong and ConcurrentHashMap.
無條件線程安全。該類的實例是可變的,但是該類具有足夠的內部同步,因此無需任何外部同步即可并發地使用該類的實例。例如 AtomicLong 和 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.
有條件的線程安全。與無條件線程安全類似,只是有些方法需要外部同步才能安全并發使用。示例包括 Collections.synchronized 包裝器返回的集合,其迭代器需要外部同步。
- **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.
非線程安全。該類的實例是可變的。要并發地使用它們,客戶端必須使用外部同步來包圍每個方法調用(或調用序列)。這樣的例子包括通用的集合實現,例如 ArrayList 和 HashMap。
- **Thread-hostile** —This class is unsafe for concurrent use even if every method invocation is 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 typically result from the failure to consider concurrency. When a class or method is found to be thread-hostile, it is typically fixed or deprecated. The generateSerialNumber method in Item 78 would be thread-hostile in the absence of internal synchronization, as discussed on page 322.
線程對立。即使每個方法調用都被外部同步包圍,該類對于并發使用也是不安全的。線程對立通常是由于在不同步的情況下修改靜態數據而導致的。沒有人故意編寫線程對立類;此類通常是由于沒有考慮并發性而導致的。當發現類或方法與線程不相容時,通常將其修復或棄用。[Item-78](/Chapter-11/Chapter-11-Item-78-Synchronize-access-to-shared-mutable-data.md) 中的 generateSerialNumber 方法在沒有內部同步的情況下是線程對立的,如第 322 頁所述。
These categories (apart from thread-hostile) correspond roughly to the thread safety annotations in Java Concurrency in Practice, which are Immutable, ThreadSafe, and NotThreadSafe [Goetz06, Appendix A]. The unconditionally and conditionally thread-safe categories in the above taxonomy are both covered under the ThreadSafe annotation.
這些類別(不包括線程對立類)大致對應于《Java Concurrency in Practice》中的線程安全注解,分別為 Immutable、ThreadSafe 和 NotThreadSafe [Goetz06, Appendix A]。上面分類中的無條件線程安全和有條件的線程安全都包含在 ThreadSafe 注解中。
Documenting a conditionally thread-safe class requires care. You must indicate which invocation sequences require external synchronization, and which lock (or in rare cases, locks) must be acquired to execute these sequences. Typically it is the lock on the instance itself, but there are exceptions. For example, the documentation for Collections.synchronizedMap says this:
在文檔中記錄一個有條件的線程安全類需要小心。你必須指出哪些調用序列需要外部同步,以及執行這些序列必須獲得哪些鎖(在極少數情況下是鎖)。通常是實例本身的鎖,但也有例外。例如,`Collections.synchronizedMap` 的文檔提到:
It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views:
當用戶遍歷其集合視圖時,必須手動同步返回的 Map:
```
Map<K, V> m = Collections.synchronizedMap(new HashMap<>());
Set<K> s = m.keySet(); // Needn't be in synchronized block
...
synchronized(m) { // Synchronizing on m, not s!
for (K key : s)
key.f();
}
```
Failure to follow this advice may result in non-deterministic behavior.
不遵循這個建議可能會導致不確定的行為。
The description of a class’s thread safety generally belongs in the class’s doc 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).
類的線程安全的描述通常屬于該類的文檔注釋,但是具有特殊線程安全屬性的方法應該在它們自己的文檔注釋中描述這些屬性。沒有必要記錄枚舉類型的不變性。除非從返回類型可以明顯看出,否則靜態工廠必須記錄返回對象的線程安全性,正如 `Collections.synchronizedMap` 所演示的那樣。
When a class commits to using a publicly accessible lock, it enables clients to execute a sequence of method invocations atomically, but this flexibility comes at a price. It is incompatible with high-performance internal concurrency control, of the sort used by concurrent collections such as ConcurrentHashMap. Also, a client can mount a denial-of-service attack by holding the publicly accessible lock for a prolonged period. This can be done accidentally or intentionally.
當一個類使用公共可訪問鎖時,它允許客戶端自動執行一系列方法調用,但是這種靈活性是有代價的。它與諸如 ConcurrentHashMap 之類的并發集合所使用的高性能內部并發控制不兼容。此外,客戶端可以通過長時間持有可公開訪問的鎖來發起拒絕服務攻擊。這可以是無意的,也可以是有意的。
To prevent this denial-of-service attack, you can use a private lock object instead of using synchronized methods (which imply a publicly accessible lock):
為了防止這種拒絕服務攻擊,你可以使用一個私有鎖對象,而不是使用同步方法(隱含一個公共可訪問的鎖):
```
// Private lock object idiom - thwarts denial-of-service attack
private final Object lock = new Object();
public void foo() {
synchronized(lock) {
...
}
}
```
Because the private lock object is inaccessible outside the class, it is impossible for clients to interfere with the object’s synchronization. In effect, we are applying the advice of Item 15 by encapsulating the lock object in the object it synchronizes.
因為私有鎖對象在類之外是不可訪問的,所以客戶端不可能干擾對象的同步。實際上,我們通過將鎖對象封裝在它同步的對象中,是在應用 [Item-15](/Chapter-4/Chapter-4-Item-15-Minimize-the-accessibility-of-classes-and-members.md) 的建議。
Note that the lock field is declared final. This prevents you from inadvertently changing its contents, which could result in catastrophic unsynchronized access (Item 78). We are applying the advice of Item 17, by minimizing the mutability of the lock field. **Lock fields should always be declared final.** This is true whether you use an ordinary monitor lock (as shown above) or a lock from the java.util.concurrent.locks package.
注意,lock 字段被聲明為 final。這可以防止你無意中更改它的內容,這可能導致災難性的非同步訪問([Item-78](/Chapter-11/Chapter-11-Item-78-Synchronize-access-to-shared-mutable-data.md))。我們正在應用 [Item-17](/Chapter-4/Chapter-4-Item-17-Minimize-mutability.md) 的建議,最小化鎖字段的可變性。**Lock 字段應該始終聲明為 final。** 無論使用普通的監視器鎖(如上所示)還是 `java.util.concurrent` 包中的鎖,都是這樣。
The private lock object idiom can be used only on unconditionally thread-safe classes. Conditionally thread-safe classes can’t use this idiom because they must document which lock their clients are to acquire when performing certain method invocation sequences.
私有鎖對象用法只能在無條件的線程安全類上使用。有條件的線程安全類不能使用這種用法,因為它們必須在文檔中記錄,在執行某些方法調用序列時要獲取哪些鎖。
The private lock object idiom is particularly well-suited to classes designed for inheritance (Item 19). If such a class were to use its instances for locking, a subclass could easily and unintentionally interfere with the operation of the base class, or vice versa. By using the same lock for different purposes, the subclass and the base class could end up “stepping on each other’s toes.” This is not just a theoretical problem; it happened with the Thread class [Bloch05, Puzzle 77].
私有鎖對象用法特別適合為繼承而設計的類([Item-19](/Chapter-4/Chapter-4-Item-19-Design-and-document-for-inheritance-or-else-prohibit-it.md))。如果這樣一個類要使用它的實例進行鎖定,那么子類很容易在無意中干擾基類的操作,反之亦然。通過為不同的目的使用相同的鎖,子類和基類最終可能「踩到對方的腳趾頭」。這不僅僅是一個理論問題,它就發生在 Thread 類中 [Bloch05, Puzzle 77]。
To summarize, 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 more flexibility to adopt a sophisticated approach to concurrency control in a later release.
總之,每個類都應該措辭嚴謹的描述或使用線程安全注解清楚地記錄其線程安全屬性。synchronized 修飾符在文檔中沒有任何作用。有條件的線程安全類必須記錄哪些方法調用序列需要外部同步,以及在執行這些序列時需要獲取哪些鎖。如果你編寫一個無條件線程安全的類,請考慮使用一個私有鎖對象來代替同步方法。這將保護你免受客戶端和子類的同步干擾,并為你提供更大的靈活性,以便在后續的版本中采用復雜的并發控制方式。
---
**[Back to contents of the chapter(返回章節目錄)](/Chapter-11/Chapter-11-Introduction.md)**
- **Previous Item(上一條目):[Item 81: Prefer concurrency utilities to wait and notify(并發實用工具優于 wait 和 notify)](/Chapter-11/Chapter-11-Item-81-Prefer-concurrency-utilities-to-wait-and-notify.md)**
- **Next Item(下一條目):[Item 83: Use lazy initialization judiciously(明智地使用延遲初始化)](/Chapter-11/Chapter-11-Item-83-Use-lazy-initialization-judiciously.md)**
- Chapter 2. Creating and Destroying Objects(創建和銷毀對象)
- Item 1: Consider static factory methods instead of constructors(考慮以靜態工廠方法代替構造函數)
- Item 2: Consider a builder when faced with many constructor parameters(在面對多個構造函數參數時,請考慮構建器)
- Item 3: Enforce the singleton property with a private constructor or an enum type(使用私有構造函數或枚舉類型實施單例屬性)
- Item 4: Enforce noninstantiability with a private constructor(用私有構造函數實施不可實例化)
- Item 5: Prefer dependency injection to hardwiring resources(依賴注入優于硬連接資源)
- Item 6: Avoid creating unnecessary objects(避免創建不必要的對象)
- Item 7: Eliminate obsolete object references(排除過時的對象引用)
- Item 8: Avoid finalizers and cleaners(避免使用終結器和清除器)
- Item 9: Prefer try with resources to try finally(使用 try-with-resources 優于 try-finally)
- Chapter 3. Methods Common to All Objects(對象的通用方法)
- Item 10: Obey the general contract when overriding equals(覆蓋 equals 方法時應遵守的約定)
- Item 11: Always override hashCode when you override equals(當覆蓋 equals 方法時,總要覆蓋 hashCode 方法)
- Item 12: Always override toString(始終覆蓋 toString 方法)
- Item 13: Override clone judiciously(明智地覆蓋 clone 方法)
- Item 14: Consider implementing Comparable(考慮實現 Comparable 接口)
- Chapter 4. Classes and Interfaces(類和接口)
- Item 15: Minimize the accessibility of classes and members(盡量減少類和成員的可訪問性)
- Item 16: In public classes use accessor methods not public fields(在公共類中,使用訪問器方法,而不是公共字段)
- Item 17: Minimize mutability(減少可變性)
- Item 18: Favor composition over inheritance(優先選擇復合而不是繼承)
- Item 19: Design and document for inheritance or else prohibit it(繼承要設計良好并且具有文檔,否則禁止使用)
- Item 20: Prefer interfaces to abstract classes(接口優于抽象類)
- Item 21: Design interfaces for posterity(為后代設計接口)
- Item 22: Use interfaces only to define types(接口只用于定義類型)
- Item 23: Prefer class hierarchies to tagged classes(類層次結構優于帶標簽的類)
- Item 24: Favor static member classes over nonstatic(靜態成員類優于非靜態成員類)
- Item 25: Limit source files to a single top level class(源文件僅限有單個頂層類)
- Chapter 5. Generics(泛型)
- Item 26: Do not use raw types(不要使用原始類型)
- Item 27: Eliminate unchecked warnings(消除 unchecked 警告)
- Item 28: Prefer lists to arrays(list 優于數組)
- Item 29: Favor generic types(優先使用泛型)
- Item 30: Favor generic methods(優先使用泛型方法)
- Item 31: Use bounded wildcards to increase API flexibility(使用有界通配符增加 API 的靈活性)
- Item 32: Combine generics and varargs judiciously(明智地合用泛型和可變參數)
- Item 33: Consider typesafe heterogeneous containers(考慮類型安全的異構容器)
- Chapter 6. Enums and Annotations(枚舉和注解)
- Item 34: Use enums instead of int constants(用枚舉類型代替 int 常量)
- Item 35: Use instance fields instead of ordinals(使用實例字段替代序數)
- Item 36: Use EnumSet instead of bit fields(用 EnumSet 替代位字段)
- Item 37: Use EnumMap instead of ordinal indexing(使用 EnumMap 替換序數索引)
- Item 38: Emulate extensible enums with interfaces(使用接口模擬可擴展枚舉)
- Item 39: Prefer annotations to naming patterns(注解優于命名模式)
- Item 40: Consistently use the Override annotation(堅持使用 @Override 注解)
- Item 41: Use marker interfaces to define types(使用標記接口定義類型)
- Chapter 7. Lambdas and Streams(λ 表達式和流)
- Item 42: Prefer lambdas to anonymous classes(λ 表達式優于匿名類)
- Item 43: Prefer method references to lambdas(方法引用優于 λ 表達式)
- Item 44: Favor the use of standard functional interfaces(優先使用標準函數式接口)
- Item 45: Use streams judiciously(明智地使用流)
- Item 46: Prefer side effect free functions in streams(在流中使用無副作用的函數)
- Item 47: Prefer Collection to Stream as a return type(優先選擇 Collection 而不是流作為返回類型)
- Item 48: Use caution when making streams parallel(謹慎使用并行流)
- Chapter 8. Methods(方法)
- Item 49: Check parameters for validity(檢查參數的有效性)
- Item 50: Make defensive copies when needed(在需要時制作防御性副本)
- Item 51: Design method signatures carefully(仔細設計方法簽名)
- Item 52: Use overloading judiciously(明智地使用重載)
- Item 53: Use varargs judiciously(明智地使用可變參數)
- Item 54: Return empty collections or arrays, not nulls(返回空集合或數組,而不是 null)
- Item 55: Return optionals judiciously(明智地的返回 Optional)
- Item 56: Write doc comments for all exposed API elements(為所有公開的 API 元素編寫文檔注釋)
- Chapter 9. General Programming(通用程序設計)
- Item 57: Minimize the scope of local variables(將局部變量的作用域最小化)
- Item 58: Prefer for-each loops to traditional for loops(for-each 循環優于傳統的 for 循環)
- Item 59: Know and use the libraries(了解并使用庫)
- Item 60: Avoid float and double if exact answers are required(若需要精確答案就應避免使用 float 和 double 類型)
- Item 61: Prefer primitive types to boxed primitives(基本數據類型優于包裝類)
- Item 62: Avoid strings where other types are more appropriate(其他類型更合適時應避免使用字符串)
- Item 63: Beware the performance of string concatenation(當心字符串連接引起的性能問題)
- Item 64: Refer to objects by their interfaces(通過接口引用對象)
- Item 65: Prefer interfaces to reflection(接口優于反射)
- Item 66: Use native methods judiciously(明智地使用本地方法)
- Item 67: Optimize judiciously(明智地進行優化)
- Item 68: Adhere to generally accepted naming conventions(遵守被廣泛認可的命名約定)
- Chapter 10. Exceptions(異常)
- Item 69: Use exceptions only for exceptional conditions(僅在確有異常條件下使用異常)
- Item 70: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors(對可恢復情況使用 checked 異常,對編程錯誤使用運行時異常)
- Item 71: Avoid unnecessary use of checked exceptions(避免不必要地使用 checked 異常)
- Item 72: Favor the use of standard exceptions(鼓勵復用標準異常)
- Item 73: Throw exceptions appropriate to the abstraction(拋出能用抽象解釋的異常)
- Item 74: Document all exceptions thrown by each method(為每個方法記錄會拋出的所有異常)
- Item 75: Include failure capture information in detail messages(異常詳細消息中應包含捕獲失敗的信息)
- Item 76: Strive for failure atomicity(盡力保證故障原子性)
- Item 77: Don’t ignore exceptions(不要忽略異常)
- Chapter 11. Concurrency(并發)
- Item 78: Synchronize access to shared mutable data(對共享可變數據的同步訪問)
- Item 79: Avoid excessive synchronization(避免過度同步)
- Item 80: Prefer executors, tasks, and streams to threads(Executor、task、流優于直接使用線程)
- Item 81: Prefer concurrency utilities to wait and notify(并發實用工具優于 wait 和 notify)
- Item 82: Document thread safety(文檔應包含線程安全屬性)
- Item 83: Use lazy initialization judiciously(明智地使用延遲初始化)
- Item 84: Don’t depend on the thread scheduler(不要依賴線程調度器)
- Chapter 12. Serialization(序列化)
- Item 85: Prefer alternatives to Java serialization(優先選擇 Java 序列化的替代方案)
- Item 86: Implement Serializable with great caution(非常謹慎地實現 Serializable)
- Item 87: Consider using a custom serialized form(考慮使用自定義序列化形式)
- Item 88: Write readObject methods defensively(防御性地編寫 readObject 方法)
- Item 89: For instance control, prefer enum types to readResolve(對于實例控制,枚舉類型優于 readResolve)
- Item 90: Consider serialization proxies instead of serialized instances(考慮以序列化代理代替序列化實例)