Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 8th, 2012  |  syntax: None  |  size: 1.26 KB  |  hits: 11  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Necessity of volatile array write while in synchronized block
  2. // Cache of byte[] data by row and column.
  3.   private volatile byte[][][] cache;
  4.  
  5.   public byte[] getData(int row, int col)
  6.   {
  7.     return cache[row][col];
  8.   }
  9.  
  10.   public void updateData(int row, int col, byte[] data)
  11.   {
  12.     synchronized(cache)
  13.     {
  14.       if (!Arrays.equals(data,cache[row][col]))
  15.       {
  16.         cache[row][col] = data;
  17.  
  18.         // Volatile write.
  19.         // The below line is intentional to ensure a volatile write is
  20.         // made to the array, since access via getData is unsynchronized.
  21.         this.cache = this.cache;
  22.  
  23.         // Notification code removed
  24.         // (mentioning it since it is the reason for synchronizing).
  25.       }
  26.     }
  27.   }
  28.        
  29. private final    byte[][][] cacheF = new ...;  // dimensions fixed?
  30.   private volatile byte[][][] cacheV = cacheF;
  31.  
  32.   public byte[] getData(int row, int col)
  33.   {
  34.     return cacheV[row][col];
  35.   }
  36.  
  37.   public void updateData(int row, int col, byte[] data)
  38.   {
  39.     synchronized(cacheF)
  40.     {
  41.       if (!Arrays.equals(data,cacheF[row][col]))
  42.       {
  43.         cacheF[row][col] = data;
  44.  
  45.         cacheV = cacheF;
  46.       }
  47.     }
  48.   }
  49.        
  50. private volatile byte[][]cache = ...;
  51. cache[row][col] = data;
  52.        
  53. private final byte[][]cache = ...;
  54. cache[row][col] = data;