## Chapter 11. Concurrency(并發)
### Item 78: Synchronize access to shared mutable data(對共享可變數據的同步訪問)
The synchronized keyword ensures that only a single thread can execute a method or block at one time. Many programmers think of synchronization solely as a means of mutual exclusion, to prevent an object from being seen in an inconsistent state by one thread while it’s being modified by another. In this view, an object is created in a consistent state (Item 17) and locked by the methods that access it. These methods observe the state and optionally cause a state transition, transforming the object from one consistent state to another. Proper use of synchronization guarantees that no method will ever observe the object in an inconsistent state.
synchronized 關鍵字確保一次只有一個線程可以執行一個方法或塊。許多程序員認為同步只是一種互斥的方法,是為防止一個線程在另一個線程修改對象時使對象處于不一致的狀態。這樣看來,對象以一致的狀態創建([Item-17](/Chapter-4/Chapter-4-Item-17-Minimize-mutability.md)),并由訪問它的方法鎖定。這些方法可以察覺當前狀態,并引起狀態轉換,將對象從一致的狀態轉換為另一個一致的狀態。正確使用同步可以保證沒有方法會讓對象處于不一致狀態。
This view is correct, but it’s only half the story. Without synchronization, one thread’s changes might not be visible to other threads. Not only does synchronization prevent threads from observing an object in an inconsistent state, but it ensures that each thread entering a synchronized method or block sees the effects of all previous modifications that were guarded by the same lock.
這種觀點是正確的,但它只是冰山一角。沒有同步,一個線程所做的的更改可能對其他線程不可見。同步不僅阻止線程察覺到處于不一致狀態的對象,而且確保每個進入同步方法或塊的線程都能察覺由同一把鎖保護的所有已修改的效果。
The language specification guarantees that reading or writing a variable is atomic unless the variable is of type long or double [JLS, 17.4, 17.7]. In other words, reading a variable other than a long or double is guaranteed to return a value that was stored into that variable by some thread, even if multiple threads modify the variable concurrently and without synchronization.
語言規范保證讀取或寫入變量是原子性的,除非變量的類型是 long 或 double [JLS, 17.4, 17.7]。換句話說,讀取 long 或 double 之外的變量將保證返回某個線程存儲在該變量中的值,即使多個線程同時修改該變量,并且沒有同步時也是如此。
You may hear it said that to improve performance, you should dispense with synchronization when reading or writing atomic data. This advice is dangerously wrong. While the language specification guarantees that a thread will not see an arbitrary value when reading a field, it does not guarantee that a value written by one thread will be visible to another. **Synchronization is required for reliable communication between threads as well as for mutual exclusion.** This is due to a part of the language specification known as the memory model, which specifies when and how changes made by one thread become visible to others [JLS, 17.4; Goetz06, 16].
你可能聽說過,為了提高性能,在讀取或寫入具有原子性的數據時應該避免同步。這種建議大錯特錯。雖然語言規范保證線程在讀取字段時不會覺察任意值,但它不保證由一個線程編寫的值對另一個線程可見。**線程之間能可靠通信以及實施互斥,同步是所必需的。** 這是由于語言規范中,稱為內存模型的部分指定了一個線程所做的更改何時以及如何對其他線程可見 [JLS, 17.4; Goetz06, 16]。
The consequences of failing to synchronize access to shared mutable data can be dire even if the data is atomically readable and writable. Consider the task of stopping one thread from another. The libraries provide the Thread.stop method, but this method was deprecated long ago because it is inherently unsafe —its use can result in data corruption. **Do not use Thread.stop.** A recommended way to stop one thread from another is to have the first thread poll a boolean field that is initially false but can be set to true by the second thread to indicate that the first thread is to stop itself. Because reading and writing a boolean field is atomic, some programmers dispense with synchronization when accessing the field:
即使數據是原子可讀和可寫的,無法同步訪問共享可變數據的后果也可能是可怕的。考慮從一個線程中使另一個線程停止的任務。庫提供了 `Thread.stop` 方法,但是這個方法很久以前就被棄用了,因為它本質上是不安全的,它的使用可能導致數據損壞。**不要使用 `Thread.stop`。** 一個建議的方法是讓第一個線程輪詢一個 boolean 字段,該字段最初為 false,但第二個線程可以將其設置為 true,以指示第一個線程要停止它自己。由于讀寫布爾字段是原子性的,一些程序員在訪問該字段時不需要同步:
```
// Broken! - How long would you expect this program to run?
public class StopThread {
private static boolean stopRequested;
public static void main(String[] args) throws InterruptedException {
Thread backgroundThread = new Thread(() -> {
int i = 0;
while (!stopRequested)
i++;
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
stopRequested = true;
}
}
```
You might expect this program to run for about a second, after which the main thread sets stopRequested to true, causing the background thread’s loop to terminate. On my machine, however, the program never terminates: the background thread loops forever!
你可能認為這個程序運行大約一秒鐘,之后主線程將 stopRequested 設置為 true,從而導致后臺線程的循環終止。然而,在我的機器上,程序永遠不會終止:后臺線程永遠循環!
The problem is that in the absence of synchronization, there is no guarantee as to when, if ever, the background thread will see the change in the value of stopRequested made by the main thread. In the absence of synchronization, it’s quite acceptable for the virtual machine to transform this code:
問題在于在缺乏同步的情況下,無法保證后臺線程何時(如果有的話)看到主線程所做的 stopRequested 值的更改。在缺乏同步的情況下,虛擬機可以很好地轉換這段代碼:
```
while (!stopRequested)
i++;
into this code:
if (!stopRequested)
while (true)
i++;
```
This optimization is known as hoisting, and it is precisely what the OpenJDK Server VM does. The result is a liveness failure: the program fails to make progress. One way to fix the problem is to synchronize access to the stopRequested field. This program terminates in about one second, as expected:
這種優化稱為提升,這正是 OpenJDK 服務器 VM 所做的。結果是活性失敗:程序無法取得進展。解決此問題的一種方法是同步對 stopRequested 字段的訪問。程序在大約一秒內結束,正如預期:
```
// Properly synchronized cooperative thread termination
public class StopThread {
private static boolean stopRequested;
private static synchronized void requestStop() {
stopRequested = true;
}
private static synchronized boolean stopRequested() {
return stopRequested;
}
public static void main(String[] args) throws InterruptedException {
Thread backgroundThread = new Thread(() -> {
int i = 0;
while (!stopRequested())
i++;
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
requestStop();
}
}
```
Note that both the write method (requestStop) and the read method (stop-Requested) are synchronized. It is not sufficient to synchronize only the write method! **Synchronization is not guaranteed to work unless both read and write operations are synchronized.** Occasionally a program that synchronizes only writes (or reads) may appear to work on some machines, but in this case, appearances are deceiving.
注意,寫方法(requestStop)和讀方法(stopRequested)都是同步的。僅同步寫方法是不夠的!**除非讀和寫操作都同步,否則不能保證同步工作。** 有時,只同步寫(或讀)的程序可能在某些機器上顯示有效,但在這種情況下,不能這么做。
The actions of the synchronized methods in StopThread would be atomic even without synchronization. In other words, the synchronization on these methods is used solely for its communication effects, not for mutual exclusion. While the cost of synchronizing on each iteration of the loop is small, there is a correct alternative that is less verbose and whose performance is likely to be better. The locking in the second version of StopThread can be omitted if stopRequested is declared volatile. While the volatile modifier performs no mutual exclusion, it guarantees that any thread that reads the field will see the most recently written value:
即使沒有同步,StopThread 中同步方法的操作也是原子性的。換句話說,這些方法的同步僅用于其通信效果,而不是互斥。雖然在循環的每個迭代上同步的成本很小,但是有一種正確的替代方法,它不那么冗長,而且性能可能更好。如果 stopRequested 聲明為 volatile,則可以省略 StopThread 的第二個版本中的鎖。雖然 volatile 修飾符不執行互斥,但它保證任何讀取字段的線程都會看到最近寫入的值:
```
// Cooperative thread termination with a volatile field
public class StopThread {
private static volatile boolean stopRequested;
public static void main(String[] args) throws InterruptedException {
Thread backgroundThread = new Thread(() -> {
int i = 0;
while (!stopRequested)
i++;
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
stopRequested = true;
}
}
```
You do have to be careful when using volatile. Consider the following method, which is supposed to generate serial numbers:
在使用 volatile 時一定要小心。考慮下面的方法,它應該生成序列號:
```
// Broken - requires synchronization!
private static volatile int nextSerialNumber = 0;
public static int generateSerialNumber() {
return nextSerialNumber++;
}
```
The intent of the method is to guarantee that every invocation returns a unique value (so long as there are no more than 2<sup>32</sup> invocations). The method’s state consists of a single atomically accessible field, nextSerialNumber, and all possible values of this field are legal. Therefore, no synchronization is necessary to protect its invariants. Still, the method won’t work properly without synchronization.
該方法的目的是確保每次調用返回一個唯一的值(只要不超過 2<sup>32</sup> 次調用)。方法的狀態由一個原子可訪問的字段 nextSerialNumber 組成,該字段的所有可能值都是合法的。因此,不需要同步來保護它的不變性。不過,如果沒有同步,該方法將無法正常工作。
The problem is that the increment operator (++) is not atomic. It performs two operations on the nextSerialNumber field: first it reads the value, and then it writes back a new value, equal to the old value plus one. If a second thread reads the field between the time a thread reads the old value and writes back a new one, the second thread will see the same value as the first and return the same serial number. This is a safety failure: the program computes the wrong results.
問題在于增量運算符 `(++)` 不是原子性的。它對 nextSerialNumber 字段執行兩個操作:首先讀取值,然后返回一個新值,舊值再加 1。如果第二個線程在讀取舊值和寫入新值之間讀取字段,則第二個線程將看到與第一個線程相同的值,并返回相同的序列號。這是一個安全故障:使程序計算錯誤的原因。
One way to fix generateSerialNumber is to add the synchronized modifier to its declaration. This ensures that multiple invocations won’t be interleaved and that each invocation of the method will see the effects of all previous invocations. Once you’ve done that, you can and should remove the volatile modifier from nextSerialNumber. To bulletproof the method, use long instead of int, or throw an exception if nextSerialNumber is about to wrap.
修復 generateSerialNumber 的一種方法是將 synchronized 修飾符添加到它的聲明中。這確保了多個調用不會交叉,并且該方法的每次調用都將看到之前所有調用的效果。一旦你這樣做了,你就可以并且應該從 nextSerialNumber 中刪除 volatile 修飾符。為了使方法更可靠,應使用 long 而不是 int,或者在 nextSerialNumber 即將超限時拋出異常。
Better still, follow the advice in Item 59 and use the class AtomicLong, which is part of java.util.concurrent.atomic. This package provides primitives for lock-free, thread-safe programming on single variables. While volatile provides only the communication effects of synchronization, this package also provides atomicity. This is exactly what we want for generateSerialNumber, and it is likely to outperform the synchronized version:
更好的方法是,遵循 [Item-59](/Chapter-9/Chapter-9-Item-59-Know-and-use-the-libraries.md) 中的建議并使用 AtomicLong 類,它是 `java.util.concurrent.atomic` 的一部分。這個包為單變量的無鎖、線程安全編程提供了基本類型。雖然 volatile 只提供同步的通信效果,但是這個包提供原子性。這正是我們想要的 generateSerialNumber,它很可能優于同步版本:
```
// Lock-free synchronization with java.util.concurrent.atomic
private static final AtomicLong nextSerialNum = new AtomicLong();
public static long generateSerialNumber() {
return nextSerialNum.getAndIncrement();
}
```
The best way to avoid the problems discussed in this item is not to share mutable data. Either share immutable data (Item 17) or don’t share at all. In other words, **confine mutable data to a single thread.** If you adopt this policy, it is important to document it so that the policy is maintained as your program evolves. It is also important to have a deep understanding of the frameworks and libraries you’re using because they may introduce threads that you are unaware of.
為避免出現本條目中討論的問題,最佳方法是不共享可變數據。要么共享不可變數據([Item-17](/Chapter-4/Chapter-4-Item-17-Minimize-mutability.md)),要么完全不共享。換句話說,**應當將可變數據限制在一個線程中。** 如果采用此策略,重要的是對其進行文檔化,以便隨著程序的發展維護該策略。深入了解你正在使用的框架和庫也很重要,因為它們可能會引入你不知道的線程。
It is acceptable for one thread to modify a data object for a while and then to share it with other threads, synchronizing only the act of sharing the object reference. Other threads can then read the object without further synchronization, so long as it isn’t modified again. Such objects are said to be effectively immutable [Goetz06, 3.5.4]. Transferring such an object reference from one thread to others is called safe publication [Goetz06, 3.5.3]. There are many ways to safely publish an object reference: you can store it in a static field as part of class initialization; you can store it in a volatile field, a final field, or a field that is accessed with normal locking; or you can put it into a concurrent collection (Item 81).
一個線程可以暫時修改一個數據對象,然后與其他線程共享,并且只同步共享對象引用的操作。然后,其他線程可以在沒有進一步同步的情況下讀取對象,只要不再次修改該對象。這些對象被認為是有效不可變的 [Goetz06, 3.5.4]。將這樣的對象引用從一個線程轉移到其他線程稱為安全發布 [Goetz06, 3.5.3]。安全地發布對象引用的方法有很多:可以將它存儲在靜態字段中,作為類初始化的一部分;你可以將其存儲在易失性字段、final 字段或使用普通鎖定訪問的字段中;或者你可以將其放入并發集合中([Item-81](/Chapter-11/Chapter-11-Item-81-Prefer-concurrency-utilities-to-wait-and-notify.md))。
In summary, **when multiple threads share mutable data, each thread that reads or writes the data must perform synchronization.** In the absence of synchronization, there is no guarantee that one thread’s changes will be visible to another thread. The penalties for failing to synchronize shared mutable data are liveness and safety failures. These failures are among the most difficult to debug. They can be intermittent and timing-dependent, and program behavior can vary radically from one VM to another. If you need only inter-thread communication, and not mutual exclusion, the volatile modifier is an acceptable form of synchronization, but it can be tricky to use correctly.
總之,**當多個線程共享可變數據時,每個讀取或寫入數據的線程都必須執行同步。** 在缺乏同步的情況下,不能保證一個線程的更改對另一個線程可見。同步共享可變數據失敗的代價是活性失敗和安全失敗。這些故障是最難調試的故障之一。它們可能是間歇性的,并與時間相關,而且程序行為可能在不同 VM 之間發生根本的變化。如果只需要線程間通信,而不需要互斥,那么 volatile 修飾符是一種可接受的同步形式,但是要想正確使用它可能會比較棘手。
---
**[Back to contents of the chapter(返回章節目錄)](/Chapter-11/Chapter-11-Introduction.md)**
- **Previous Item(上一條目):[Item 77: Don’t ignore exceptions(不要忽略異常)](/Chapter-10/Chapter-10-Item-77-Don’t-ignore-exceptions.md)**
- **Next Item(下一條目):[Item 79: Avoid excessive synchronization(避免過度同步)](/Chapter-11/Chapter-11-Item-79-Avoid-excessive-synchronization.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(考慮以序列化代理代替序列化實例)