As known, the arrays, even when volatile, do not provide volatile semantics when reading or writing elements, concurrent accessing the k-th element of the array requires an explicit volatile read. This volatile read is performed through the Unsafe.getObjectVolatile().
I want to know , only declaring one object, not array without volatile, using Unsafe.getObjectVolatile() to read it can get the same effect as declaring it with volatile?
Just look at the implementation of java.util.concurrent.atomic.AtomicReferenceArray
It internally uses a private final Object[] array field and does fenced accesses to it through unsafe, e.g. here is the element setter:
public final void set(int i, E newValue) {
unsafe.putObjectVolatile(array, checkedByteOffset(i), newValue);
}
Do note that the internal and unsupported Unsafe API will probably go away/become inaccessible with java 9, so if you want to use it prepare for some forward-porting effort once varhandles arrive. And/or consider implementing a fallback codepath.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With