java handle_在Java 9中使用VarHandle的正确方法?

它被用于例如AtomicReference,其中以前在Java 8中使用了sun.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);

}

在这里,该指针与字段偏移一起用于访问字段.但这是不安全的,因为这个字段的偏移量可能会很长,你可能实际上正在访问完全不同的内容.然而,以这种方式执行性能优势(它告诉VM使用专门的cpu指令),并且因为其他人使用sun.misc.Unsafe,即使它是一个内部和不安全的API.

VarHandles的一部分目的是用一个安全的等价物替换sun.misc.Unsafe中的操作.哪个在the JEP中说明:

Define a standard means to invoke the equivalents of varIoUs java.util.concurrent.atomic and sun.misc.Unsafe operations…

Goals:

The following are required goals:

Safety. It must not be possible to place the Java Virtual Machine in a corrupt memory state. For example,a field of an object can only be updated with instances that are castable to the field type,or an array element can only be accessed within an array if the array index is within the array bounds.

Integrity. Access to a field of an object follows the same access rules as with getfield and putfield byte codes in addition to the constraint that a final field of an object cannot be updated. (Note: such safety and integrity rules also apply to MethodHandles giving read or write access to a field.)

Performance. The performance characteristics must be the same as or similar to equivalent sun.misc.Unsafe operations (specifically,generated assembler code should be almost identical modulo certain safety checks that cannot be folded away).

Usability. The API must be better than the sun.misc.Unsafe API.

所以在Java 9中,这些方法看起来像这样:

public final void lazySet(V newValue) {

VALUE.setRelease(this,newValue);

}

public final boolean compareAndSet(V expectedValue,V newValue) {

return VALUE.compareAndSet(this,expectedValue,newValue);

}

其中VALUE是一个VarHandle定义如下:

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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值