I have a question regarding the Java Memory Model. Here is a simple class presenting the problem:
public class ImmutableIntArray {
private final int[] array;
public ImmutableIntArray() {
array = new int[10];
for (int i = 0; i < 10; i++) {
array[i] = i;
}
}
// Will always return the correct value?
public int get(int index) {
return array[index];
}
}
As far as I know the JMM guarantees that the value of final fields will be visible to other threads after construction. But I want to ensure that other threads will see the most recent version of data stored in the array after construction.
Of course the code above is just a simple example presenting the problem, actually I want to implement a simple cache for direct byte buffers and I wouldn't like to rely on some Collection classes. Currently I am using a ReentrantReadWriteLock to ensure the correct behaviour but I would like avoid it if it is possible.