-
|
In your PS class, use the VarHandle class to access the attributes key and value, which are declared volatile. My confusion is that if the attribute has been declared volatile, is there any difference between using VarHandle's set, setVolatile, and setRelease? Similarly, is there any difference between using get, getVolatile, and getAccquire? In the java.util.concurrent.atomic.AtomicReference class of JDK21, the comments on the set and get methods make me think that if the attribute has been declared volatile, using VarHandle's set, setVolatile, and setRelease should be the same. public class AtomicReference<V> implements java.io.Serializable {
private static final long serialVersionUID = -1848883965231344442L;
private static final VarHandle VALUE;
static {
try {
MethodHandles.Lookup l = MethodHandles.lookup();
VALUE = l.findVarHandle(AtomicReference.class, "value", Object.class);
} catch (ReflectiveOperationException e) {
throw new ExceptionInInitializerError(e);
}
}
@SuppressWarnings("serial") // Conditionally serializable
private volatile V value;
/**
* Creates a new AtomicReference with the given initial value.
*
* @param initialValue the initial value
*/
public AtomicReference(V initialValue) {
value = initialValue;
}
/**
* Creates a new AtomicReference with null initial value.
*/
public AtomicReference() {
}
/**
* Returns the current value,
* with memory effects as specified by {@link VarHandle#getVolatile}.
*
* @return the current value
*/
public final V get() {
return value;
}
/**
* Sets the value to {@code newValue},
* with memory effects as specified by {@link VarHandle#setVolatile}.
*
* @param newValue the new value
*/
public final void set(V newValue) {
value = newValue;
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
|
The VarHandle takes precedence where its mode determines the memory semantics. When absent then the field's mode does, making it a volatile read or write. While not necessary if used consistently, its nice as a visual hint and added safety if accidentally missed since it uses the strongest memory mode. The JavaDoc is simply deferring to the more exhaustive explanation since the default memory mode is a volatile operation. You can experiment by adapting jcstress samples if you want to see that in action. |
Beta Was this translation helpful? Give feedback.
The VarHandle takes precedence where its mode determines the memory semantics. When absent then the field's mode does, making it a volatile read or write. While not necessary if used consistently, its nice as a visual hint and added safety if accidentally missed since it uses the strongest memory mode. The JavaDoc is simply deferring to the more exhaustive explanation since the default memory mode is a volatile operation. You can experiment by adapting jcstress samples if you want to see that in action.