Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About Unsafe.getObjectVolatile usage

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?

like image 932
taigetco Avatar asked Mar 17 '26 15:03

taigetco


1 Answers

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.

like image 184
the8472 Avatar answered Mar 19 '26 04:03

the8472



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!