<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>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                ## 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)**
                  <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>

                              哎呀哎呀视频在线观看