The right way to use varhandle in Java 9?

I spent a lot of time investigating some new features of Java 9, but I didn't find any useful and practical examples

Consider the next code snippet to create a varhandle:

class Counter {
    int i;
}

class VarHandleInAction {
    static final VarHandle VH_COUNTER_FIELD_I;

    static {
        try {
            VH_COUNTER_FIELD_I = MethodHandles.lookup().
                in(Counter.class).
                findVarHandle(Counter.class,"i",int.class);
        } catch (Exception e) {
            // ...
        }
    }
}

But what's next? I mean, how do I use this variable handle? Can you provide any real examples?

Solution

It is used, for example, in atomicreference, where sun. Com was previously used in Java 8 misc. Unsafe:

public final void lazySet(V newValue) {
    unsafe.putOrderedObject(this,valueOffset,newValue);
}

public final boolean compareAndSet(V expect,V update) {
    return unsafe.compareAndSwapObject(this,expect,update);
}

Here, the pointer is used to access the field together with the field offset But this is not safe, because the offset of this field may be very long, and you may actually be accessing completely different content However, the performance advantage is performed in this way (it tells the VM to use dedicated CPU instructions), and because others use sun misc. Unsafe, even if it is an internal and unsafe API

Part of the purpose of varhandles is to replace sun with a safe equivalent misc. Operations in unsafe Which is stated in the JEP:

So in Java 9, these methods look like this:

public final void lazySet(V newValue) {
    VALUE.setRelease(this,newValue);
}

public final boolean compareAndSet(V expectedValue,V newValue) {
    return VALUE.compareAndSet(this,expectedValue,newValue);
}

Where value is a varhandle, which is defined as follows:

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 Error(e);
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>