
Untitled
By: a guest on
May 8th, 2012 | syntax:
None | size: 1.26 KB | hits: 11 | expires: Never
Necessity of volatile array write while in synchronized block
// Cache of byte[] data by row and column.
private volatile byte[][][] cache;
public byte[] getData(int row, int col)
{
return cache[row][col];
}
public void updateData(int row, int col, byte[] data)
{
synchronized(cache)
{
if (!Arrays.equals(data,cache[row][col]))
{
cache[row][col] = data;
// Volatile write.
// The below line is intentional to ensure a volatile write is
// made to the array, since access via getData is unsynchronized.
this.cache = this.cache;
// Notification code removed
// (mentioning it since it is the reason for synchronizing).
}
}
}
private final byte[][][] cacheF = new ...; // dimensions fixed?
private volatile byte[][][] cacheV = cacheF;
public byte[] getData(int row, int col)
{
return cacheV[row][col];
}
public void updateData(int row, int col, byte[] data)
{
synchronized(cacheF)
{
if (!Arrays.equals(data,cacheF[row][col]))
{
cacheF[row][col] = data;
cacheV = cacheF;
}
}
}
private volatile byte[][]cache = ...;
cache[row][col] = data;
private final byte[][]cache = ...;
cache[row][col] = data;