<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                ## 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)**
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看