【volatile-面接】メモリバリア

2078 ワード

Javaでのvolatile
 
Javaはvolatileキーワードもサポートしていますが、他の異なる用途で使用されています.volatileが1つの役割ドメインに使用される場合、Javaは以下のことを保証する.
  • (Javaのすべてのバージョンに適用)volatile変数の読み取りと書き込みには、グローバルなソートがあります.すなわち、各スレッドがvolatile役割ドメインにアクセスすると、キャッシュされた値を使用するのではなく、実行を続行する前に現在の値が読み出されます.(ただし、volatileの役割ドメインを頻繁に読み書きする場合の読み書きの相対的な順序は保証されません.つまり、通常、これは有用なスレッド構築ではありません).
  • (Java 5以降のバージョンに適用)volatileの読み取りと書き込みはhappens-before関係を確立し、反発ロックの申請と解放に類似している[1].
  • volatileを使用すると、ロックを使用するよりも速くなりますが、動作しない場合があります.volatileの使用範囲はJava 5で拡張され、特に二重チェックロックが正しく動作するようになった[2].
    次のようになります.
    Double-checked locking is actually OK as of Java 5 provided that you make the instance reference volatile. So for example, if we needed to pass in a database connection to getInstance(), then this would be OK:
    public class MyFactory {
      private static volatile MyFactory instance;
    
      public static MyFactory getInstance(Connection conn)
           throws IOException {
        if (instance == null) {
          synchronized (MyFactory.class) {
            if (instance == null)
              instance = new MyFactory(conn);
          }
        }
        return instance;  
      }
    
      private MyFactory(Connection conn) throws IOException {
        // init factory using the database connection passed in
      }
    }
    

    Note that this is OK as of Java 5 because the definition of volatile was specifically changed to make it OK. Accessing a volatile variable has the semantics of synchronization as of Java 5. In other words Java 5 ensures that the unsycnrhonized volatile read must happen after the write has taken place, and the reading thread will see the correct values of all fields on MyFactory.
    1  Section 17.4.4: Synchronization Order The Java Language Specification, 3rd Edition. Sun Microsystems. 2005 [2010-11-22].  2 Neil Coffey. Double-checked Locking (DCL) and how to fix it. Javamex. [2009-09-19]  
     
    参照先:
    Double-checked Locking (DCL) and how to fix it (ctd)
    https://www.javamex.com/tutorials/double_checked_locking_fixing.shtml