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

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                ## Chapter 11. Concurrency(并發) ### Item 83: Use lazy initialization judiciously(明智地使用延遲初始化) Lazy initialization is the act of delaying the initialization of a field until its value is needed. If the value is never needed, the field is never initialized. This technique is applicable to both static and instance fields. While lazy initialization is primarily an optimization, it can also be used to break harmful circularities in class and instance initialization [Bloch05, Puzzle 51]. 延遲初始化是延遲字段的初始化,直到需要它的值。如果不需要該值,則不會初始化字段。這種技術既適用于靜態字段,也適用于實例字段。雖然延遲初始化主要作為一種優化手段,它還可用于避免類與實例初始化中循環依賴的問題 [Bloch05, Puzzle 51]。 As is the case for most optimizations, the best advice for lazy initialization is “don’t do it unless you need to” (Item 67). Lazy initialization is a double-edged sword. It decreases the cost of initializing a class or creating an instance, at the expense of increasing the cost of accessing the lazily initialized field. Depending on what fraction of these fields eventually require initialization, how expensive it is to initialize them, and how often each one is accessed once initialized, lazy initialization can (like many “optimizations”) actually harm performance. 與大多數優化一樣,延遲初始化的最佳建議是「除非需要,否則不要這樣做」(第67項)。延遲初始化是一把雙刃劍。它降低了初始化類或創建實例的成本,代價是增加了訪問延遲初始化字段的成本。根據這些字段中最終需要初始化的部分、初始化它們的開銷以及初始化后訪問每個字段的頻率,延遲初始化實際上會損害性能(就像許多「優化」一樣)。 That said, lazy initialization has its uses. If a field is accessed only on a fraction of the instances of a class and it is costly to initialize the field, then lazy initialization may be worthwhile. The only way to know for sure is to measure the performance of the class with and without lazy initialization. 延遲初始化也有它的用途。如果一個字段只在類的一小部分實例上訪問,并且初始化該字段的代價很高,那么延遲初始化可能是值得的。唯一確定的方法是以使用和不使用延遲初始化的效果對比來度量類的性能。 In the presence of multiple threads, lazy initialization is tricky. If two or more threads share a lazily initialized field, it is critical that some form of synchronization be employed, or severe bugs can result (Item 78). All of the initialization techniques discussed in this item are thread-safe. 在存在多個線程的情況下,使用延遲初始化很棘手。如果兩個或多個線程共享一個延遲初始化的字段,那么必須使用某種形式的同步,否則會導致嚴重的錯誤([Item-78](/Chapter-11/Chapter-11-Item-78-Synchronize-access-to-shared-mutable-data.md))。本條目討論的所有初始化技術都是線程安全的。 **Under most circumstances, normal initialization is preferable to lazy initialization.** Here is a typical declaration for a normally initialized instance field. Note the use of the final modifier (Item 17): **在大多數情況下,常規初始化優于延遲初始化。** 下面是一個使用常規初始化的實例字段的典型聲明。注意 final 修飾符的使用([Item-17](/Chapter-4/Chapter-4-Item-17-Minimize-mutability.md)): ``` // Normal initialization of an instance field private final FieldType field = computeFieldValue(); ``` **If you use lazy initialization to break an initialization circularity, use a synchronized accessor** because it is the simplest, clearest alternative: **如果您使用延遲初始化來取代初始化 circularity,請使用同步訪問器**,因為它是最簡單、最清晰的替代方法: ``` // Lazy initialization of instance field - synchronized accessor private FieldType field; private synchronized FieldType getField() { if (field == null) field = computeFieldValue(); return field; } ``` Both of these idioms (normal initialization and lazy initialization with a synchronized accessor) are unchanged when applied to static fields, except that you add the static modifier to the field and accessor declarations. 這兩種習慣用法(使用同步訪問器進行常規初始化和延遲初始化)在應用于靜態字段時都沒有改變,只是在字段和訪問器聲明中添加了 static 修飾符。 **If you need to use lazy initialization for performance on a static field, use the lazy initialization holder class idiom.** This idiom exploits the guarantee that a class will not be initialized until it is used [JLS, 12.4.1]. Here’s how it looks: **如果需要在靜態字段上使用延遲初始化來提高性能,use the lazy initialization holder class idiom.** 這個用法可保證一個類在使用之前不會被初始化 [JLS, 12.4.1]。它是這樣的: ``` // Lazy initialization holder class idiom for static fields private static class FieldHolder { static final FieldType field = computeFieldValue(); } private static FieldType getField() { return FieldHolder.field; } ``` When getField is invoked for the first time, it reads FieldHolder.field for the first time, causing the initialization of the FieldHolder class. The beauty of this idiom is that the getField method is not synchronized and performs only a field access, so lazy initialization adds practically nothing to the cost of access. A typical VM will synchronize field access only to initialize the class. Once the class is initialized, the VM patches the code so that subsequent access to the field does not involve any testing or synchronization. 第一次調用 getField 時,它執行 FieldHolder.field,導致初始化 FieldHolder 類。這個習慣用法的優點是 getField 方法不是同步的,只執行字段訪問,所以延遲初始化實際上不會增加訪問成本。典型的 VM 只會同步字段訪問來初始化類。初始化類之后,VM 會對代碼進行修補,這樣對字段的后續訪問就不會涉及任何測試或同步。 **If you need to use lazy initialization for performance on an instance field, use the double-check idiom.** This idiom avoids the cost of locking when accessing the field after initialization (Item 79). The idea behind the idiom is to check the value of the field twice (hence the name double-check): once without locking and then, if the field appears to be uninitialized, a second time with locking. Only if the second check indicates that the field is uninitialized does the call initialize the field. Because there is no locking once the field is initialized, it is critical that the field be declared volatile (Item 78). Here is the idiom: 如果需要使用延遲初始化來提高實例字段的性能,請使用雙重檢查模式。這個模式避免了初始化后訪問字段時的鎖定成本([Item-79](/Chapter-11/Chapter-11-Item-79-Avoid-excessive-synchronization.md))。這個模式背后的思想是兩次檢查字段的值(因此得名 double check):一次沒有鎖定,然后,如果字段沒有初始化,第二次使用鎖定。只有當第二次檢查指示字段未初始化時,調用才初始化字段。由于初始化字段后沒有鎖定,因此將字段聲明為 volatile 非常重要([Item-78](/Chapter-11/Chapter-11-Item-78-Synchronize-access-to-shared-mutable-data.md))。下面是這個模式的示例: ``` // Double-check idiom for lazy initialization of instance fields private volatile FieldType field; private FieldType getField() { FieldType result = field; if (result == null) { // First check (no locking) synchronized(this) { if (field == null) // Second check (with locking) field = result = computeFieldValue(); } } return result; } ``` This code may appear a bit convoluted. In particular, the need for the local variable (result) may be unclear. What this variable does is to ensure that field is read only once in the common case where it’s already initialized. 這段代碼可能看起來有點復雜。特別是不清楚是否需要局部變量(result)。該變量的作用是確保 field 在已經初始化的情況下只讀取一次。 While not strictly necessary, this may improve performance and is more elegant by the standards applied to low-level concurrent programming. On my machine, the method above is about 1.4 times as fast as the obvious version without a local variable. While you can apply the double-check idiom to static fields as well, there is no reason to do so: the lazy initialization holder class idiom is a better choice. 雖然不是嚴格必需的,但這可能會提高性能,而且與低級并發編程相比,這更優雅。在我的機器上,上述方法的速度大約是沒有局部變量版本的 1.4 倍。雖然您也可以將雙重檢查模式應用于靜態字段,但是沒有理由這樣做:the lazy initialization holder class idiom is a better choice. Two variants of the double-check idiom bear noting. Occasionally, you may need to lazily initialize an instance field that can tolerate repeated initialization. If you find yourself in this situation, you can use a variant of the double-check idiom that dispenses with the second check. It is, not surprisingly, known as the single-check idiom. Here is how it looks. Note that field is still declared volatile: 雙重檢查模式的兩個變體值得注意。有時候,您可能需要延遲初始化一個實例字段,該字段可以容忍重復初始化。如果您發現自己處于這種情況,您可以使用雙重檢查模式的變體來避免第二個檢查。毫無疑問,這就是所謂的「單檢查」模式。它是這樣的。注意,field 仍然聲明為 volatile: ``` // Single-check idiom - can cause repeated initialization! private volatile FieldType field; private FieldType getField() { FieldType result = field; if (result == null) field = result = computeFieldValue(); return result; } ``` All of the initialization techniques discussed in this item apply to primitive fields as well as object reference fields. When the double-check or single-check idiom is applied to a numerical primitive field, the field’s value is checked against 0 (the default value for numerical primitive variables) rather than null. 本條目中討論的所有初始化技術都適用于基本字段和對象引用字段。當雙檢查或單檢查模式應用于數值基本類型字段時,將根據 0(數值基本類型變量的默認值)而不是 null 檢查字段的值。 If you don’t care whether every thread recalculates the value of a field, and the type of the field is a primitive other than long or double, then you may choose to remove the volatile modifier from the field declaration in the single-check idiom. This variant is known as the racy single-check idiom. It speeds up field access on some architectures, at the expense of additional initializations (up to one per thread that accesses the field). This is definitely an exotic technique, not for everyday use. 如果您不關心每個線程是否都會重新計算字段的值,并且字段的類型是 long 或 double 之外的基本類型,那么您可以選擇在單檢查模式中從字段聲明中刪除 volatile 修飾符。這種變體稱為原生單檢查模式。它加快了某些架構上的字段訪問速度,代價是需要額外的初始化(每個訪問該字段的線程最多需要一個初始化)。這絕對是一種奇特的技術,不是日常使用的。 In summary, you should initialize most fields normally, not lazily. If you must initialize a field lazily in order to achieve your performance goals or to break a harmful initialization circularity, then use the appropriate lazy initialization technique. For instance fields, it is the double-check idiom; for static fields, the lazy initialization holder class idiom. For instance fields that can tolerate repeated initialization, you may also consider the single-check idiom. 總之,您應該正常初始化大多數字段,而不是延遲初始化。如果必須延遲初始化字段以實現性能目標或 break a harmful initialization circularity,則使用適當的延遲初始化技術。對于字段,使用雙重檢查模式;對于靜態字段,the lazy initialization holder class idiom. 例如,可以容忍重復初始化的實例字段,您還可以考慮單檢查模式。 --- **[Back to contents of the chapter(返回章節目錄)](/Chapter-11/Chapter-11-Introduction.md)** - **Previous Item(上一條目):[Item 82: Document thread safety(文檔應包含線程安全屬性)](/Chapter-11/Chapter-11-Item-82-Document-thread-safety.md)** - **Next Item(下一條目):[Item 84: Don’t depend on the thread scheduler(不要依賴線程調度器)](/Chapter-11/Chapter-11-Item-84-Don’t-depend-on-the-thread-scheduler.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>

                              哎呀哎呀视频在线观看