From other questions, I learned that the elements of a volatile array are not volatile. Only the reference itself is volatile.
volatile[] int data;
Thread A: data[4] = 457;
Thread B: System.out.println(data[4]);
Here, Thread B might never see the updated value.
Which options/alternatives do I have to achieve the same thing? I would like to avoid having to synchronize the array, since it is hardly ever altered. However, it is being read a lot by some threads. Synchronizing it will very likely lower the throughput, which is very important in this example.
Is my only option a copy-on-write data-structure here? That is, copying the array into a new array and update the array reference afterwards.
Are there any other options? I read somewhere that encapsulating the array into a class (with only one member, the array) achieves the same thing, but I doubt that is true. I cannot see how that might help.
Please note that my target JVM is 1.4. This means I cannot use the java.util.concurrent
package.
-------------- edit edit edit --------------
In Java volatile array? I read that re-assigning the array reference achieves the volatility semantics. This should give the correct results:
volatile[] int data;
Thread A: data[4] = 457;
Thread A: data = data;
Thread B: System.out.println(data[4]);
Is this valid on older JVMs?