Код: Выделить всё
public class MyClass {
private volatile Object refValue;
private static final VarHandle REF_VALUE_HANDLE;
static {
try {
REF_VALUE_HANDLE = MethodHandles.lookup()
.findVarHandle(MyClass.class, "refValue", Object.class);
} catch (ReflectiveOperationException e) {
throw new Error(e);
}
}
public Object get1() {
return this.refValue;
}
public Object get2() {
return REF_VALUE_HANDLE.get(this);
}
public Object get3() {
return REF_VALUE_HANDLE.getVolatile(this);
}
public void set1(Object newValue) {
this.refValue = newValue;
}
public void set2(Object newValue) {
REF_VALUE_HANDLE.set(this, newValue);
}
public void set3(Object newValue) {
REF_VALUE_HANDLE.setVolatile(this, newValue);
}
}
< /code>
Если переменная была объявлена волатильной, есть ли какая -либо разница между различными методами набора и получения выше? />
Возвращает текущее значение, с эффектами памяти, как указано Varhandle. getVolatile. < /p>
< /blockquote>
Устанавливает значение в NewValue, с эффектами памяти, как указано Varhandle. SetVolatile. < /p>
< /blockquote>
public class AtomicReference 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;
}
}
Подробнее здесь: https://stackoverflow.com/questions/795 ... -varhandle