爱游戏全站app官网入口-爱游戏官网

java底层魔术类unsafe用法简述 -爱游戏全站app官网入口

2023-08-10,,

java中没有指针,不能直接对内存地址的变量进行控制,但java提供了一个特殊的类unsafe工具类来间接实现。unsafe主要提供一些用于执行低级别、不安全操作的方法,如直接访问系统内存资源、自主管理内存资源等,这些方法在提升java运行效率、增强java语言底层资源操作能力方面起到了很大的作用 。正如其名字unsafe,直接去使用这个工具类是不安全的,它能直接在硬件层(内存上)修改访问变量,而无视各种访问修饰符的限制。它几乎所有的公共方法api都是本地方法,这些方法是使用c/c 方法实现的,它越过了虚拟机层面,直接在操作系统本地执行。因为这是一个底层类,如果在不了解其内部原理、未掌握其使用技巧的情况下,我们直接使用unsafe类可能会造成一些意想不到或未知的错误,所以它被限制开发者直接使用,只能由jdk类库的维护者使用。如果您喜欢阅读jdk的源码,那么你会发现在各种并发工具类的内部常常见到这个类的踪影,它们经常通过这个类的一些方法根据相应内存地址在内存上直接cas修改访问共享变量的值。

unsafe类在oracle的官方jdk中没有提供源码,我们只能通过idea的反编译工具看到反编译后的源代码,因此我们看不到方法注释。而只openjdk中带有所有jdk的源代码,这里使用openjdk作参考讲解材料。以下是openjdk中unsafe的类注释

a collection of methods for performing low-level, unsafe operations. although the class and all methods are public, use of this class is limited because only trusted code can obtain instances of it.

直译过来大致意思是:此类拥有一组用于执行低级,不安全操作的方法。 尽管此类和所有方法都是公共的,但是由于只有可信代码才能获取该类的实例,因此此类的使用受到限制。

可以看出构造方法被私有化,只能通过静态方法getunsafe()才能获取此unsafe单例对象,而此静态方法的使用也是受到限制的,只能由jdk中的其它类来调用,普通开发者使用此方法将抛出异常。

    private unsafe() {}
    private static final unsafe theunsafe = new unsafe();
    @callersensitive
public static unsafe getunsafe() {
class caller = reflection.getcallerclass(); //调用者class对象
if (!vm.issystemdomainloader(caller.getclassloader())) //判断调用者的类加载器是否为系统类加载器
//不是java_home/jre/lib目录下jar包中的类来调用此方法getunsafe()就会抛出异常
throw new securityexception("unsafe");
return theunsafe;
}

此方法getunsafe()上的注释也说:

为调用提供执行不安全操作的能力。返回的unsafe对象应由调用方小心保护,因为它可用于在任意内存地址处读取和写入数据。 绝不能将其传递给不受信任的代码。此类中的大多数方法都是非常底层的,并且对应于少量的硬件指令(在典型的机器上)。 应鼓励编译器相应地优化这些方法,而不是使用unsafe类来控制。

getunsafe()要求jdk类库自身调用,当然将开发者可以将自己定义的类放在jdk系统类库中,但这种方式明显是不安全、不方便的,其可行性太低。倘若开发者的确需要使用unsafe类,我们可以使用反射的方式获取unsafe实例。
    private static unsafe getunsafebyreflect() {
try {
field f = unsafe.class.getdeclaredfield("theunsafe");
f.setaccessible(true);
return (unsafe) f.get(null);
} catch (exception e) {
throw new error(e);
}
}

使用反射方式,在开发者的classpath中获取到unsafe实例

package com.aaxis;
import java.lang.reflect.field;
import sun.misc.unsafe;
public class student {
private int stuid;
private string name;
private int age;
private static final long stuid_offset;
private static final unsafe unsafe = getunsafebyreflect();
static {
try {
stuid_offset = unsafe.objectfieldoffset(student.class.getdeclaredfield("stuid"));
} catch (nosuchfieldexception | securityexception e) {
throw new error(e);
} }
private static unsafe getunsafebyreflect() {
try {
field f = unsafe.class.getdeclaredfield("theunsafe");
f.setaccessible(true);
return (unsafe) f.get(null);
} catch (exception e) {
throw new error(e);
}
} public static void unsafedprintstuid() {
student student = new student(34124, "小黄");
int stuid = unsafe.getint(student, stuid_offset); system.out.println(student.getname() "学号:" stuid);
}
public static void main(string[] args) {
unsafedprintstuid();
}
//.....
}

在classpath环境中使用unsafe

unsafe类的主要功能如图:

注意:因为反射中使用field描述实例变量和静态变量,现在将实例变量和静态变量统称为字段。

获取字段相对偏移量

/**
* 根据反射的字段f,获取相应实例变量的偏移量
* 此偏移量是实例变量的起始地址与对象的起始地址之差,对于一确定的java类,某字段与对象之间的起始地址之差是常数,
* 静态变量的偏移量与此类似
*/
public native long staticfieldoffset(field f);
//根据反射的字段f,获取相应静态变量的偏移量(静态变量的起始地址与相应静态区klass对象起始地址之差)
public native long objectfieldoffset(field f);

这里提到了字段的偏移量,这与java对象的内存布局有密切关系。java对象由对象头和实际数据两部分组成。

下图中markword包含对象的hashcode、锁信息、垃圾回收的分代信息等,占32/64位;class metadata pointer表示一个此对象数据类型的class对象(虚拟机中的klass对象)的指针,占32/64位;arraylength是数组对象特有的内容,表示数组的长度,占32位。数组对象的实际数据是各个元素的值或引用,普通对象的实际数据是各实例字段的值或引用。另外为了快速内存分配、快速内存寻址、提高性能,java语言规范要求java对象要做内存对齐处理,每个对象占用的内存字节数必须是8的倍数,若不是则要填零补足对齐。

从下图可以看出,字段与对象头之间的偏移量是固定的,只要知道字段的相对偏移量和对象起始地址,我们就能获取此字段的绝对内存地址(fieldaddress=objaddress fieldoffset),根据此绝对内存地址,我们就能忽略访问修饰符的限制而可直接读取/修改此字段的值或引用。

数组对象的元素内存定址,相对对于普通对象的字段定址有些不一样,它要先计算出对象头的长度,作为基础偏移量;由于数组元素的数据类型是相同的,每个元素的值或引用所占内存空间是相同的,因此将元素值或引用或占内存作为每两相邻元素的相对偏移量。根据对象起始位置、基础偏移量、相邻元素相对偏移量及数组下标,就可以获取到某个元素值或引用的绝对内存地址(itemaddress=arrayaddress baseoffset index*indexoffset),进而通过绝对内存地址读取或修改此元素的值或引用。

根据字段偏移量设置/获取字段值

    //根据反射的字段f,获取相应的静态变量的值
public native object staticfieldbase(field f); /**
*参数o是字段所属的对象,offset表示相对偏移量,参数x是此字段要设置的新值
*/ /*字段是引用数据类型*/
public native object getobject(object o, long offset);//获取字段值
public native void putobject(object o, long offset, object x);//设置字段值 /*字段为基本数据类型*/
public native void putint(object o, long offset, int x);
public native int getint(object o, long offset);
public native boolean getboolean(object o, long offset);
public native void putboolean(object o, long offset, boolean x);
public native byte getbyte(object o, long offset);
public native void putbyte(object o, long offset, byte x);
public native short getshort(object o, long offset);
public native void putshort(object o, long offset, short x);
public native char getchar(object o, long offset);
public native void putchar(object o, long offset, char x);
public native long getlong(object o, long offset);
public native void putlong(object o, long offset, long x);
public native float getfloat(object o, long offset);
public native void putfloat(object o, long offset, float x);
public native double getdouble(object o, long offset);
public native void putdouble(object o, long offset, double x);

 使用示例:

我将一个自定义的普通(编译后的)java类放在jdk类库的charset.jar包中,这个student类使用了unsafe类。

student.class的部分反编译源码

student部分代码

测试unsafe能否忽略访问限制,读取私有变量

package other;
import sun.awt.student;
public class unsafetest {
public static void main(string[] args) {
student.unsafedprintstuid();
}
}

控制台输出结果正确

volatile版本根据字段偏移量设置/获取字段值(加上volatile语义)

保证对其他线程的可见性(只有字段被volatile修饰时有效)

    //volatile形式地获取字段值,即使在多线条件下,从主内存中获取值,使当前线程的工作内存的缓存值失效
public native object getobjectvolatile(object o, long offset);
//volatile形式地设置字段值,即使在多线条件下,设置的值将只保存到主内存中,不加载到线程本地缓存,保证可见性
public native void putobjectvolatile(object o, long offset, object x);
public native int getintvolatile(object o, long offset);
public native void putintvolatile(object o, long offset, int x);
public native boolean getbooleanvolatile(object o, long offset);
public native void putbooleanvolatile(object o, long offset, boolean x);
public native byte getbytevolatile(object o, long offset);
public native void putbytevolatile(object o, long offset, byte x);
public native short getshortvolatile(object o, long offset);
public native void putshortvolatile(object o, long offset, short x);
public native char getcharvolatile(object o, long offset);
public native void putcharvolatile(object o, long offset, char x);
public native long getlongvolatile(object o, long offset);
public native void putlongvolatile(object o, long offset, long x);
public native float getfloatvolatile(object o, long offset);
public native void putfloatvolatile(object o, long offset, float x);
public native double getdoublevolatile(object o, long offset);
public native void putdoublevolatile(object o, long offset, double x);

有序延迟化地设置字段值

有序延迟化设值,对其他线程不保证可见性
    //有序延迟化地设置字段值,
public native void putorderedobject(object o, long offset, object x);
/** ordered/lazy version of {@link #putintvolatile(object, long, int)} */
public native void putorderedint(object o, long offset, int x);
/** ordered/lazy version of {@link #putlongvolatile(object, long, long)} */
public native void putorderedlong(object o, long offset, long x);

数组相关的偏移量

    //第一个元素与数组对象两者间起始地址之差(首元素与对象头的相对偏移量)
public native int arraybaseoffset(class arrayclass); //相邻元素间相对偏移量的位移表示(返回值的二进制形式的有效位数是x,那么相邻元素的偏移量就是2的x次方)
public native int arrayindexscale(class arrayclass);

 使用示例:

java.util.concurrent.atomic.atomicintegerarray包下的atomicintegerarray结合以上两个方法,进行数组元素地址定位。

class atomicintegerarray implements java.io.serializable {
private static final long serialversionuid = 2862133569453604235l; private static final unsafe unsafe = unsafe.getunsafe();
private static final int base = unsafe.arraybaseoffset(int[].class);
private static final int shift;
private final int[] array;
static {
int scale = unsafe.arrayindexscale(int[].class);
if ((scale & (scale - 1)) != 0)
throw new error("data type scale not a power of two");
shift = 31 - integer.numberofleadingzeros(scale);
}
private long checkedbyteoffset(int i) {
if (i < 0 || i >= array.length)
throw new indexoutofboundsexception("index " i); return byteoffset(i);
}
private static long byteoffset(int i) {
return ((long) i << shift) base;
}
public final void set(int i, int newvalue) {
unsafe.putintvolatile(array, checkedbyteoffset(i), newvalue);
}
}

atomicintegerarray部分代码

创建java类

    /**
* 让虚拟机知道我们定义一个类,但不进行安全检查。
* 默认情况下,类加载器和保护域来自调用者的类。
*/
public native class defineclass(string name, byte[] b, int off, int len,
classloader loader,
protectiondomain protectiondomain); /*
* 在类加载器和系统字典(system dictionary)不知道的情况下根据字节码数据定义一个匿名的class对象,相当于创建了一个java类
* @params hostclass context for linkage, access control, protection domain, and class loader
* @params data 字节码文件对应的字节数组
* @params cppatches where non-null entries exist, they replace corresponding cp entries in data
*/
public native class defineanonymousclass(class hostclass, byte[] data, object[] cppatches);

java类初始化

shouldbeinitialized(class)方法检测class对应的java类是否被初始化
ensureclassinitialized(class)方法强制java类初始化,若没初始化则进行初始化。
这两个方法常与staticfieldbase(field)一起使用,因为如果java类没有被初始化,静态变量便没有初始化,就不能直接获取静态变量的引用。
  /**
* detect if the given class may need to be initialized. this is often
* needed in conjunction with obtaining the static field base of a
* class.
* @return false only if a call to {@code ensureclassinitialized} would have no effect
*/
public native boolean shouldbeinitialized(class c); /**
* ensure the given class has been initialized. this is often
* needed in conjunction with obtaining the static field base of a
* class.
*/
public native void ensureclassinitialized(class c);

 使用示例:

java.lang.invoke.directmethodhandle中的checkinitialized(membername)方法调用了以上两个与类初始化相关的方法

根据class创建对象

仅通过class对象就可以创建此类的实例对象,而且不需要调用其构造函数、初始化代码、jvm安全检查,等,。它抑制修饰符检测,也就是即使构造器是private修饰的也能通过此方法实例化,只需提类对象即可创建相应的对象 .

    /** allocate an instance but do not run any constructor.
initializes the class if it has not yet been. */
public native object allocateinstance(class cls)
throws instantiationexception;

 使用示例:

employe类的唯一构造方法被私有化,外界不能直接创建此类的对象。但通过"constructor.setaccessible(true)"将私有构造器设为外部可访问,使用反射机制也能创建一个employee对象。

package other;
import sun.misc.unsafe;
import java.lang.reflect.field; public class employee {
private static int count;
private static long countl=1000;
private long id;
private string name;
private int sex;// 1代表男性,0代表女性
private long mgrid=11111;
static {
count = 1000;//目前员工人数的基数
}
private employee() {
sex = 1;//默认为男性
name = "";
count ;
countl ;
}
@override
public string tostring() {
return "{employee [id=" id ", name=" name ", sex=" sex ", mgrid=" mgrid
"]}" " ,{count=" count ", countlong=" countl "}";
}
}
class employeetest {
private static final unsafe unsafe;
static {
try {
field f = unsafe.class.getdeclaredfield("theunsafe");
f.setaccessible(true);
unsafe = (unsafe) f.get(null);
} catch (exception e) {
throw new error(e);
}
}
public static void main(string[] args) throws exception {
employee employee = (employee) unsafe.allocateinstance(employee.class);
system.out.println(employee); /* class clazz = employee.class;
constructor constructor = clazz.getdeclaredconstructor();
constructor.setaccessible(true);
employee emp = constructor.newinstance();
system.out.println(emp);*/
}
}

反射与unsafe创建对象

两种方式创建的对象tostring()信息
unsafe创建的对象
反射创建的对象

从上面的控制台输出信息可以看出,反射与unsafe能均创建一个构造方法被私有化的对象。不同之处在于allocateinstance(class)方法创建对象过程中不会进行对象初始化,但会进行类初始化;即不会执行实例变量初始化赋值、不执行构造代码块、不调用构造方法,但会执行静态变量的初始化赋值、执行静态代码块。

cas是java并发编程的最底层依据,它实现了非阻塞式地更新共享变量,自旋锁与乐观锁的实现均依赖它。

   /**
* cas更新共享变量
*
* @param o 字段所属对象
* @param offset 字段的相对偏移量
* @param expected 预期值
* @param x 更新值
* @return 更新成功则返回true
*/
public final native boolean compareandswapobject(object o, long offset, object expected, object x); public final native boolean compareandswapint(object o, long offset, int expected, int x); public final native boolean compareandswaplong(object o, long offset, long expected, long x);

 使用示例:

同步器aqs的compareandsetxxx()方法都直接委托上面的cas方法实现的

根据内存地址,设置/获取对应的值

   /**
* 参数address是绝对内存地址,参数x是设定的值
* 如果address是零或不是通过allocmemery()方法分配的地址,那么结果未定义
*/
public native byte getbyte(long address);
public native void putbyte(long address, byte x);
/** @see #getbyte(long) */
public native short getshort(long address);
/** @see #putbyte(long, byte) */
public native void putshort(long address, short x);
/** @see #getbyte(long) */
public native char getchar(long address);
/** @see #putbyte(long, byte) */
public native void putchar(long address, char x);
/** @see #getbyte(long) */
public native int getint(long address);
/** @see #putbyte(long, byte) */
public native void putint(long address, int x);
/** @see #getbyte(long) */
public native long getlong(long address);
/** @see #putbyte(long, byte) */
public native void putlong(long address, long x);
/** @see #getbyte(long) */
public native float getfloat(long address);
/** @see #putbyte(long, byte) */
public native void putfloat(long address, float x);
/** @see #getbyte(long) */
public native double getdouble(long address);
/** @see #putbyte(long, byte) */
public native void putdouble(long address, double x);

根据内存地址设置/获取指针

    //根据内存地址获取一个指针
public native long getaddress(long address); //根据内存地址设置一个指针,adress是内存地址,x是指定的指针值
public native void putaddress(long address, long x);

分配、扩展、释放内存

   //分配一块指定的内存空间,返回一个指向此内存起始位置的指针
public native long allocatememory(long bytes); //扩展内存
public native long reallocatememory(long address, long bytes); //在指定的内存块填充值
public native void setmemory(object o, long offset, long bytes, byte value); public void setmemory(long address, long bytes, byte value) {
setmemory(null, address, bytes, value);
}
//将一处内存的数据复制另一处内存
public native void copymemory(object srcbase, long srcoffset,
object destbase, long destoffset,
long bytes);
public void copymemory(long srcaddress, long destaddress, long bytes) {
copymemory(null, srcaddress, null, destaddress, bytes);
}
//释放内存
public native void freememory(long address);

 使用示例:

java.nio包下的directbytebuffer类的构造方法调用unsafe.allocatememory(int)分配初始条件下的的内存缓冲区

directbytebuffer的静态内部类deallocator的run()调用unsafe.freememory(long)释放相应地址的内存空间

获取指定宽度、内存页大小等系统软硬件信息,这些信息对于本地内存的分配、使用、寻址很重要。

    //本地指针宽度,通常是4或8
public native int addresssize(); /**
*内存页的大小,它总是2的幂次方
*/
public native int pagesize();

 使用示例:

sun.nio.ch包下nativeobject类的addresssize()方法直接委托unsafe.addresssize()实现

java.nio包下bit类pagesize()方法:当pagesize非法时,将unsafe.pagesize()作为返回值

可以看出addresssize()、 pagesize()方法的调用者都是nio相关类,这是因为nio是直接使用jvm堆外的本地内存。

唤醒/休眠线程

    public native void unpark(object thread);//唤醒
    public native void park(boolean isabsolute, long time);//休眠

以上两个方法是"等待/通知模型"的关键,它们的并发编程中常使用到的底层方法。以上两个方法主要被locksupport类直接引用,locksupport.parkutil(long) 、 locksupport.upark(thread)方法中没有其他逻辑,就是直接委托以上两个方法实现的。

 使用示例:

抢锁与释放锁(已经被弃用)

   //获取锁对象
@deprecated
public native void monitorenter(object o);
//释放锁对象
@deprecated
public native void monitorexit(object o);
//尝试获取锁对象
@deprecated
public native boolean trymonitorenter(object o);

在java 8中引入,用于定义内存屏障(也称内存栅栏,内存栅障,屏障指令等,是一类同步屏障指令,是cpu或编译器在对内存随机访问的操作中的一个同步点,使得此点之前的所有读写操作都执行后才可以开始执行此点之后的操作),避免代码重排序

    /**
* 内存屏障,禁止load重排序。屏障前不能重排序load,且只能在屏障后load或store
*/
public native void loadfence(); /**
* 内存屏障,禁止store重排序。 屏障前不能重排序store操作,且只能在屏障后load或store
*/
public native void storefence(); /**
* 内存屏障,禁止store load重排序。
*/
public native void fullfence();

 使用示例:

loadfence()方法在stampedlock的validate方法有使用到,stampedlock是为了防止cas更新时出现aba问题而在jdk1.8新引入的并发工具。

openjdk1.8中含注释的unsafe类源代码

/*
* 爱游戏全站app官网入口 copyright (c) 2000, 2013, oracle and/or its affiliates. all rights reserved.
* do not alter or remove 爱游戏全站app官网入口 copyright notices or this file header.
*
* this code is free software; you can redistribute it and/or modify it
* under the terms of the gnu general public license version 2 only, as
* published by the free software foundation. oracle designates this
* particular file as subject to the "classpath" exception as provided
* by oracle in the license file that accompanied this code.
*
* this code is distributed in the hope that it will be useful, but without
* any warranty; without even the implied warranty of merchantability or
* fitness for a particular purpose. see the gnu general public license
* version 2 for more details (a copy is included in the license file that
* accompanied this code).
*
* you should have received a copy of the gnu general public license version
* 2 along with this work; if not, write to the free software foundation,
* inc., 51 franklin st, fifth floor, boston, ma 02110-1301 usa.
*
* please contact oracle, 500 oracle parkway, redwood shores, ca 94065 usa
* or visit www.oracle.com if you need additional information or have any
* questions.
*/ package sun.misc; import java.security.*;
import java.lang.reflect.*; import sun.reflect.callersensitive;
import sun.reflect.reflection; /**
* a collection of methods for performing low-level, unsafe operations.
* although the class and all methods are public, use of this class is
* limited because only trusted code can obtain instances of it.
*
* @author john r. rose
* @see #getunsafe
*/ public final class unsafe { private static native void registernatives();
static {
registernatives();
sun.reflect.reflection.registermethodstofilter(unsafe.class, "getunsafe");
} private unsafe() {} private static final unsafe theunsafe = new unsafe(); /**
* provides the caller with the capability of performing unsafe
* operations.
*
*

the returned unsafe object should be carefully guarded
* by the caller, since it can be used to read and write data at arbitrary
* memory addresses. it must never be passed to untrusted code.
*
*

most methods in this class are very low-level, and correspond to a
* small number of hardware instructions (on typical machines). compilers
* are encouraged to optimize these methods accordingly.
*
*

here is a suggested idiom for using unsafe operations:
*
*


* class mytrustedclass {
* private static final unsafe unsafe = unsafe.getunsafe();
* ...
* private long mycountaddress = ...;
* public int getcount() { return unsafe.getbyte(mycountaddress); }
* }
*

*
* (it may assist compilers to make the local variable be
* final.)
*
* @exception securityexception if a security manager exists and its
* checkpropertiesaccess method doesn't allow
* access to the system properties.
*/
@callersensitive
public static unsafe getunsafe() {
class caller = reflection.getcallerclass();
if (!vm.issystemdomainloader(caller.getclassloader()))
throw new securityexception("unsafe");
return theunsafe;
} /// peek and poke operations
/// (compilers should optimize these to memory ops) // these work on object fields in the java heap.
// they will not work on elements of packed arrays. /**
* fetches a value from a given java variable.
* more specifically, fetches a field or array element within the given
* object o at the given offset, or (if o is
* null) from the memory address whose numerical value is the given
* offset.
*


* the results are undefined unless one of the following cases is true:
*


    *
  • the offset was obtained from {@link #objectfieldoffset} on
    * the {@link java.lang.reflect.field} of some java field and the object
    * referred to by o is of a class compatible with that
    * field's class.
    *
    *
  • the offset and object reference o (either null or
    * non-null) were both obtained via {@link #staticfieldoffset}
    * and {@link #staticfieldbase} (respectively) from the
    * reflective {@link field} representation of some java field.
    *
    *
  • the object referred to by o is an array, and the offset
    * is an integer of the form b n*s, where n is
    * a valid index into the array, and b and s are
    * the values obtained by {@link #arraybaseoffset} and {@link
    * #arrayindexscale} (respectively) from the array's class. the value
    * referred to is the nth element of the array.
    *
    *

*


* if one of the above cases is true, the call references a specific java
* variable (field or array element). however, the results are undefined
* if that variable is not in fact of the type returned by this method.
*


* this method refers to a variable by means of two parameters, and so
* it provides (in effect) a double-register addressing mode
* for java variables. when the object reference is null, this method
* uses its offset as an absolute address. this is similar in operation
* to methods such as {@link #getint(long)}, which provide (in effect) a
* single-register addressing mode for non-java variables.
* however, because java variables may have a different layout in memory
* from non-java variables, programmers should not assume that these
* two addressing modes are ever equivalent. also, programmers should
* remember that offsets from the double-register addressing mode cannot
* be portably confused with longs used in the single-register addressing
* mode.
*
* @param o java heap object in which the variable resides, if any, else
* null
* @param offset indication of where the variable resides in a java heap
* object, if any, else a memory address locating the variable
* statically
* @return the value fetched from the indicated java variable
* @throws runtimeexception no defined exceptions are thrown, not even
* {@link nullpointerexception}
*/
public native int getint(object o, long offset); /**
* stores a value into a given java variable.
*


* the first two parameters are interpreted exactly as with
* {@link #getint(object, long)} to refer to a specific
* java variable (field or array element). the given value
* is stored into that variable.
*


* the variable must be of the same type as the method
* parameter x.
*
* @param o java heap object in which the variable resides, if any, else
* null
* @param offset indication of where the variable resides in a java heap
* object, if any, else a memory address locating the variable
* statically
* @param x the value to store into the indicated java variable
* @throws runtimeexception no defined exceptions are thrown, not even
* {@link nullpointerexception}
*/
public native void putint(object o, long offset, int x); /**
* fetches a reference value from a given java variable.
* @see #getint(object, long)
*/
public native object getobject(object o, long offset); /**
* stores a reference value into a given java variable.
*


* unless the reference x being stored is either null
* or matches the field type, the results are undefined.
* if the reference o is non-null, car marks or
* other store barriers for that object (if the vm requires them)
* are updated.
* @see #putint(object, int, int)
*/
public native void putobject(object o, long offset, object x); /** @see #getint(object, long) */
public native boolean getboolean(object o, long offset);
/** @see #putint(object, int, int) */
public native void putboolean(object o, long offset, boolean x);
/** @see #getint(object, long) */
public native byte getbyte(object o, long offset);
/** @see #putint(object, int, int) */
public native void putbyte(object o, long offset, byte x);
/** @see #getint(object, long) */
public native short getshort(object o, long offset);
/** @see #putint(object, int, int) */
public native void putshort(object o, long offset, short x);
/** @see #getint(object, long) */
public native char getchar(object o, long offset);
/** @see #putint(object, int, int) */
public native void putchar(object o, long offset, char x);
/** @see #getint(object, long) */
public native long getlong(object o, long offset);
/** @see #putint(object, int, int) */
public native void putlong(object o, long offset, long x);
/** @see #getint(object, long) */
public native float getfloat(object o, long offset);
/** @see #putint(object, int, int) */
public native void putfloat(object o, long offset, float x);
/** @see #getint(object, long) */
public native double getdouble(object o, long offset);
/** @see #putint(object, int, int) */
public native void putdouble(object o, long offset, double x); /**
* this method, like all others with 32-bit offsets, was native
* in a previous release but is now a wrapper which simply casts
* the offset to a long value. it provides backward compatibility
* with bytecodes compiled against 1.4.
* @deprecated as of 1.4.1, cast the 32-bit offset argument to a long.
* see {@link #staticfieldoffset}.
*/
@deprecated
public int getint(object o, int offset) {
return getint(o, (long)offset);
} /**
* @deprecated as of 1.4.1, cast the 32-bit offset argument to a long.
* see {@link #staticfieldoffset}.
*/
@deprecated
public void putint(object o, int offset, int x) {
putint(o, (long)offset, x);
} /**
* @deprecated as of 1.4.1, cast the 32-bit offset argument to a long.
* see {@link #staticfieldoffset}.
*/
@deprecated
public object getobject(object o, int offset) {
return getobject(o, (long)offset);
} /**
* @deprecated as of 1.4.1, cast the 32-bit offset argument to a long.
* see {@link #staticfieldoffset}.
*/
@deprecated
public void putobject(object o, int offset, object x) {
putobject(o, (long)offset, x);
} /**
* @deprecated as of 1.4.1, cast the 32-bit offset argument to a long.
* see {@link #staticfieldoffset}.
*/
@deprecated
public boolean getboolean(object o, int offset) {
return getboolean(o, (long)offset);
} /**
* @deprecated as of 1.4.1, cast the 32-bit offset argument to a long.
* see {@link #staticfieldoffset}.
*/
@deprecated
public void putboolean(object o, int offset, boolean x) {
putboolean(o, (long)offset, x);
} /**
* @deprecated as of 1.4.1, cast the 32-bit offset argument to a long.
* see {@link #staticfieldoffset}.
*/
@deprecated
public byte getbyte(object o, int offset) {
return getbyte(o, (long)offset);
} /**
* @deprecated as of 1.4.1, cast the 32-bit offset argument to a long.
* see {@link #staticfieldoffset}.
*/
@deprecated
public void putbyte(object o, int offset, byte x) {
putbyte(o, (long)offset, x);
} /**
* @deprecated as of 1.4.1, cast the 32-bit offset argument to a long.
* see {@link #staticfieldoffset}.
*/
@deprecated
public short getshort(object o, int offset) {
return getshort(o, (long)offset);
} /**
* @deprecated as of 1.4.1, cast the 32-bit offset argument to a long.
* see {@link #staticfieldoffset}.
*/
@deprecated
public void putshort(object o, int offset, short x) {
putshort(o, (long)offset, x);
} /**
* @deprecated as of 1.4.1, cast the 32-bit offset argument to a long.
* see {@link #staticfieldoffset}.
*/
@deprecated
public char getchar(object o, int offset) {
return getchar(o, (long)offset);
} /**
* @deprecated as of 1.4.1, cast the 32-bit offset argument to a long.
* see {@link #staticfieldoffset}.
*/
@deprecated
public void putchar(object o, int offset, char x) {
putchar(o, (long)offset, x);
} /**
* @deprecated as of 1.4.1, cast the 32-bit offset argument to a long.
* see {@link #staticfieldoffset}.
*/
@deprecated
public long getlong(object o, int offset) {
return getlong(o, (long)offset);
} /**
* @deprecated as of 1.4.1, cast the 32-bit offset argument to a long.
* see {@link #staticfieldoffset}.
*/
@deprecated
public void putlong(object o, int offset, long x) {
putlong(o, (long)offset, x);
} /**
* @deprecated as of 1.4.1, cast the 32-bit offset argument to a long.
* see {@link #staticfieldoffset}.
*/
@deprecated
public float getfloat(object o, int offset) {
return getfloat(o, (long)offset);
} /**
* @deprecated as of 1.4.1, cast the 32-bit offset argument to a long.
* see {@link #staticfieldoffset}.
*/
@deprecated
public void putfloat(object o, int offset, float x) {
putfloat(o, (long)offset, x);
} /**
* @deprecated as of 1.4.1, cast the 32-bit offset argument to a long.
* see {@link #staticfieldoffset}.
*/
@deprecated
public double getdouble(object o, int offset) {
return getdouble(o, (long)offset);
} /**
* @deprecated as of 1.4.1, cast the 32-bit offset argument to a long.
* see {@link #staticfieldoffset}.
*/
@deprecated
public void putdouble(object o, int offset, double x) {
putdouble(o, (long)offset, x);
} // these work on values in the c heap. /**
* fetches a value from a given memory address. if the address is zero, or
* does not point into a block obtained from {@link #allocatememory}, the
* results are undefined.
*
* @see #allocatememory
*/
public native byte getbyte(long address); /**
* stores a value into a given memory address. if the address is zero, or
* does not point into a block obtained from {@link #allocatememory}, the
* results are undefined.
*
* @see #getbyte(long)
*/
public native void putbyte(long address, byte x); /** @see #getbyte(long) */
public native short getshort(long address);
/** @see #putbyte(long, byte) */
public native void putshort(long address, short x);
/** @see #getbyte(long) */
public native char getchar(long address);
/** @see #putbyte(long, byte) */
public native void putchar(long address, char x);
/** @see #getbyte(long) */
public native int getint(long address);
/** @see #putbyte(long, byte) */
public native void putint(long address, int x);
/** @see #getbyte(long) */
public native long getlong(long address);
/** @see #putbyte(long, byte) */
public native void putlong(long address, long x);
/** @see #getbyte(long) */
public native float getfloat(long address);
/** @see #putbyte(long, byte) */
public native void putfloat(long address, float x);
/** @see #getbyte(long) */
public native double getdouble(long address);
/** @see #putbyte(long, byte) */
public native void putdouble(long address, double x); /**
* fetches a native pointer from a given memory address. if the address is
* zero, or does not point into a block obtained from {@link
* #allocatememory}, the results are undefined.
*
*

if the native pointer is less than 64 bits wide, it is extended as
* an unsigned number to a java long. the pointer may be indexed by any
* given byte offset, simply by adding that offset (as a simple integer) to
* the long representing the pointer. the number of bytes actually read
* from the target address maybe determined by consulting {@link
* #addresssize}.
*
* @see #allocatememory
*/
public native long getaddress(long address); /**
* stores a native pointer into a given memory address. if the address is
* zero, or does not point into a block obtained from {@link
* #allocatememory}, the results are undefined.
*
*

the number of bytes actually written at the target address maybe
* determined by consulting {@link #addresssize}.
*
* @see #getaddress(long)
*/
public native void putaddress(long address, long x); /// wrappers for malloc, realloc, free: /**
* allocates a new block of native memory, of the given size in bytes. the
* contents of the memory are uninitialized; they will generally be
* garbage. the resulting native pointer will never be zero, and will be
* aligned for all value types. dispose of this memory by calling {@link
* #freememory}, or resize it with {@link #reallocatememory}.
*
* @throws illegalargumentexception if the size is negative or too large
* for the native size_t type
*
* @throws outofmemoryerror if the allocation is refused by the system
*
* @see #getbyte(long)
* @see #putbyte(long, byte)
*/
public native long allocatememory(long bytes); /**
* resizes a new block of native memory, to the given size in bytes. the
* contents of the new block past the size of the old block are
* uninitialized; they will generally be garbage. the resulting native
* pointer will be zero if and only if the requested size is zero. the
* resulting native pointer will be aligned for all value types. dispose
* of this memory by calling {@link #freememory}, or resize it with {@link
* #reallocatememory}. the address passed to this method may be null, in
* which case an allocation will be performed.
*
* @throws illegalargumentexception if the size is negative or too large
* for the native size_t type
*
* @throws outofmemoryerror if the allocation is refused by the system
*
* @see #allocatememory
*/
public native long reallocatememory(long address, long bytes); /**
* sets all bytes in a given block of memory to a fixed value
* (usually zero).
*
*

this method determines a block's base address by means of two parameters,
* and so it provides (in effect) a double-register addressing mode,
* as discussed in {@link #getint(object,long)}. when the object reference is null,
* the offset supplies an absolute base address.
*
*

the stores are in coherent (atomic) units of a size determined
* by the address and length parameters. if the effective address and
* length are all even modulo 8, the stores take place in 'long' units.
* if the effective address and length are (resp.) even modulo 4 or 2,
* the stores take place in units of 'int' or 'short'.
*
* @since 1.7
*/
public native void setmemory(object o, long offset, long bytes, byte value); /**
* sets all bytes in a given block of memory to a fixed value
* (usually zero). this provides a single-register addressing mode,
* as discussed in {@link #getint(object,long)}.
*
*

equivalent to setmemory(null, address, bytes, value).
*/
public void setmemory(long address, long bytes, byte value) {
setmemory(null, address, bytes, value);
} /**
* sets all bytes in a given block of memory to a copy of another
* block.
*
*

this method determines each block's base address by means of two parameters,
* and so it provides (in effect) a double-register addressing mode,
* as discussed in {@link #getint(object,long)}. when the object reference is null,
* the offset supplies an absolute base address.
*
*

the transfers are in coherent (atomic) units of a size determined
* by the address and length parameters. if the effective addresses and
* length are all even modulo 8, the transfer takes place in 'long' units.
* if the effective addresses and length are (resp.) even modulo 4 or 2,
* the transfer takes place in units of 'int' or 'short'.
*
* @since 1.7
*/
public native void copymemory(object srcbase, long srcoffset,
object destbase, long destoffset,
long bytes);
/**
* sets all bytes in a given block of memory to a copy of another
* block. this provides a single-register addressing mode,
* as discussed in {@link #getint(object,long)}.
*
* equivalent to copymemory(null, srcaddress, null, destaddress, bytes).
*/
public void copymemory(long srcaddress, long destaddress, long bytes) {
copymemory(null, srcaddress, null, destaddress, bytes);
} /**
* disposes of a block of native memory, as obtained from {@link
* #allocatememory} or {@link #reallocatememory}. the address passed to
* this method may be null, in which case no action is taken.
*
* @see #allocatememory
*/
public native void freememory(long address); /// random queries /**
* this constant differs from all results that will ever be returned from
* {@link #staticfieldoffset}, {@link #objectfieldoffset},
* or {@link #arraybaseoffset}.
*/
public static final int invalid_field_offset = -1; /**
* returns the offset of a field, truncated to 32 bits.
* this method is implemented as follows:
*


* public int fieldoffset(field f) {
* if (modifier.isstatic(f.getmodifiers()))
* return (int) staticfieldoffset(f);
* else
* return (int) objectfieldoffset(f);
* }
*

* @deprecated as of 1.4.1, use {@link #staticfieldoffset} for static
* fields and {@link #objectfieldoffset} for non-static fields.
*/
@deprecated
public int fieldoffset(field f) {
if (modifier.isstatic(f.getmodifiers()))
return (int) staticfieldoffset(f);
else
return (int) objectfieldoffset(f);
} /**
* returns the base address for accessing some static field
* in the given class. this method is implemented as follows:
*

* public object staticfieldbase(class c) {
* field[] fields = c.getdeclaredfields();
* for (int i = 0; i < fields.length; i ) {
* if (modifier.isstatic(fields[i].getmodifiers())) {
* return staticfieldbase(fields[i]);
* }
* }
* return null;
* }
*

* @deprecated as of 1.4.1, use {@link #staticfieldbase(field)}
* to obtain the base pertaining to a specific {@link field}.
* this method works only for jvms which store all statics
* for a given class in one place.
*/
@deprecated
public object staticfieldbase(class c) {
field[] fields = c.getdeclaredfields();
for (int i = 0; i < fields.length; i ) {
if (modifier.isstatic(fields[i].getmodifiers())) {
return staticfieldbase(fields[i]);
}
}
return null;
} /**
* report the location of a given field in the storage allocation of its
* class. do not expect to perform any sort of arithmetic on this offset;
* it is just a cookie which is passed to the unsafe heap memory accessors.
*
*

any given field will always have the same offset and base, and no
* two distinct fields of the same class will ever have the same offset
* and base.
*
*

as of 1.4.1, offsets for fields are represented as long values,
* although the sun jvm does not use the most significant 32 bits.
* however, jvm implementations which store static fields at absolute
* addresses can use long offsets and null base pointers to express
* the field locations in a form usable by {@link #getint(object,long)}.
* therefore, code which will be ported to such jvms on 64-bit platforms
* must preserve all bits of static field offsets.
* @see #getint(object, long)
*/
public native long staticfieldoffset(field f); /**
* report the location of a given static field, in conjunction with {@link
* #staticfieldbase}.
*

do not expect to perform any sort of arithmetic on this offset;
* it is just a cookie which is passed to the unsafe heap memory accessors.
*
*

any given field will always have the same offset, and no two distinct
* fields of the same class will ever have the same offset.
*
*

as of 1.4.1, offsets for fields are represented as long values,
* although the sun jvm does not use the most significant 32 bits.
* it is hard to imagine a jvm technology which needs more than
* a few bits to encode an offset within a non-array object,
* however, for consistency with other methods in this class,
* this method reports its result as a long value.
* @see #getint(object, long)
*/
public native long objectfieldoffset(field f); /**
* report the location of a given static field, in conjunction with {@link
* #staticfieldoffset}.
*

fetch the base "object", if any, with which static fields of the
* given class can be accessed via methods like {@link #getint(object,
* long)}. this value may be null. this value may refer to an object
* which is a "cookie", not guaranteed to be a real object, and it should
* not be used in any way except as argument to the get and put routines in
* this class.
*/
public native object staticfieldbase(field f); /**
* detect if the given class may need to be initialized. this is often
* needed in conjunction with obtaining the static field base of a
* class.
* @return false only if a call to {@code ensureclassinitialized} would have no effect
*/
public native boolean shouldbeinitialized(class c); /**
* ensure the given class has been initialized. this is often
* needed in conjunction with obtaining the static field base of a
* class.
*/
public native void ensureclassinitialized(class c); /**
* report the offset of the first element in the storage allocation of a
* given array class. if {@link #arrayindexscale} returns a non-zero value
* for the same class, you may use that scale factor, together with this
* base offset, to form new offsets to access elements of arrays of the
* given class.
*
* @see #getint(object, long)
* @see #putint(object, long, int)
*/
public native int arraybaseoffset(class arrayclass); /** the value of {@code arraybaseoffset(boolean[].class)} */
public static final int array_boolean_base_offset
= theunsafe.arraybaseoffset(boolean[].class); /** the value of {@code arraybaseoffset(byte[].class)} */
public static final int array_byte_base_offset
= theunsafe.arraybaseoffset(byte[].class); /** the value of {@code arraybaseoffset(short[].class)} */
public static final int array_short_base_offset
= theunsafe.arraybaseoffset(short[].class); /** the value of {@code arraybaseoffset(char[].class)} */
public static final int array_char_base_offset
= theunsafe.arraybaseoffset(char[].class); /** the value of {@code arraybaseoffset(int[].class)} */
public static final int array_int_base_offset
= theunsafe.arraybaseoffset(int[].class); /** the value of {@code arraybaseoffset(long[].class)} */
public static final int array_long_base_offset
= theunsafe.arraybaseoffset(long[].class); /** the value of {@code arraybaseoffset(float[].class)} */
public static final int array_float_base_offset
= theunsafe.arraybaseoffset(float[].class); /** the value of {@code arraybaseoffset(double[].class)} */
public static final int array_double_base_offset
= theunsafe.arraybaseoffset(double[].class); /** the value of {@code arraybaseoffset(object[].class)} */
public static final int array_object_base_offset
= theunsafe.arraybaseoffset(object[].class); /**
* report the scale factor for addressing elements in the storage
* allocation of a given array class. however, arrays of "narrow" types
* will generally not work properly with accessors like {@link
* #getbyte(object, int)}, so the scale factor for such classes is reported
* as zero.
*
* @see #arraybaseoffset
* @see #getint(object, long)
* @see #putint(object, long, int)
*/
public native int arrayindexscale(class arrayclass); /** the value of {@code arrayindexscale(boolean[].class)} */
public static final int array_boolean_index_scale
= theunsafe.arrayindexscale(boolean[].class); /** the value of {@code arrayindexscale(byte[].class)} */
public static final int array_byte_index_scale
= theunsafe.arrayindexscale(byte[].class); /** the value of {@code arrayindexscale(short[].class)} */
public static final int array_short_index_scale
= theunsafe.arrayindexscale(short[].class); /** the value of {@code arrayindexscale(char[].class)} */
public static final int array_char_index_scale
= theunsafe.arrayindexscale(char[].class); /** the value of {@code arrayindexscale(int[].class)} */
public static final int array_int_index_scale
= theunsafe.arrayindexscale(int[].class); /** the value of {@code arrayindexscale(long[].class)} */
public static final int array_long_index_scale
= theunsafe.arrayindexscale(long[].class); /** the value of {@code arrayindexscale(float[].class)} */
public static final int array_float_index_scale
= theunsafe.arrayindexscale(float[].class); /** the value of {@code arrayindexscale(double[].class)} */
public static final int array_double_index_scale
= theunsafe.arrayindexscale(double[].class); /** the value of {@code arrayindexscale(object[].class)} */
public static final int array_object_index_scale
= theunsafe.arrayindexscale(object[].class); /**
* report the size in bytes of a native pointer, as stored via {@link
* #putaddress}. this value will be either 4 or 8. note that the sizes of
* other primitive types (as stored in native memory blocks) is determined
* fully by their information content.
*/
public native int addresssize(); /** the value of {@code addresssize()} */
public static final int address_size = theunsafe.addresssize(); /**
* report the size in bytes of a native memory page (whatever that is).
* this value will always be a power of two.
*/
public native int pagesize(); /// random trusted operations from jni: /**
* tell the vm to define a class, without security checks. by default, the
* class loader and protection domain come from the caller's class.
*/
public native class defineclass(string name, byte[] b, int off, int len,
classloader loader,
protectiondomain protectiondomain); /**
* define a class but do not make it known to the class loader or system dictionary.
*


* for each cp entry, the corresponding cp patch must either be null or have
* the a format that matches its tag:
*


    *
  • integer, long, float, double: the corresponding wrapper object type from java.lang
    *
  • utf8: a string (must have suitable syntax if used as signature or name)
    *
  • class: any java.lang.class object
    *
  • string: any object (not just a java.lang.string)
    *
  • interfacemethodref: (nyi) a method handle to invoke on that call site's arguments
    *

* @params hostclass context for linkage, access control, protection domain, and class loader
* @params data bytes of a class file
* @params cppatches where non-null entries exist, they replace corresponding cp entries in data
*/
public native class defineanonymousclass(class hostclass, byte[] data, object[] cppatches); /** allocate an instance but do not run any constructor.
initializes the class if it has not yet been. */
public native object allocateinstance(class cls)
throws instantiationexception; /** lock the object. it must get unlocked via {@link #monitorexit}. */
@deprecated
public native void monitorenter(object o); /**
* unlock the object. it must have been locked via {@link
* #monitorenter}.
*/
@deprecated
public native void monitorexit(object o); /**
* tries to lock the object. returns true or false to indicate
* whether the lock succeeded. if it did, the object must be
* unlocked via {@link #monitorexit}.
*/
@deprecated
public native boolean trymonitorenter(object o); /** throw the exception without telling the verifier. */
public native void throwexception(throwable ee); /**
* atomically update java variable to x if it is currently
* holding expected.
* @return true if successful
*/
public final native boolean compareandswapobject(object o, long offset,
object expected,
object x); /**
* atomically update java variable to x if it is currently
* holding expected.
* @return true if successful
*/
public final native boolean compareandswapint(object o, long offset,
int expected,
int x); /**
* atomically update java variable to x if it is currently
* holding expected.
* @return true if successful
*/
public final native boolean compareandswaplong(object o, long offset,
long expected,
long x); /**
* fetches a reference value from a given java variable, with volatile
* load semantics. otherwise identical to {@link #getobject(object, long)}
*/
public native object getobjectvolatile(object o, long offset); /**
* stores a reference value into a given java variable, with
* volatile store semantics. otherwise identical to {@link #putobject(object, long, object)}
*/
public native void putobjectvolatile(object o, long offset, object x); /** volatile version of {@link #getint(object, long)} */
public native int getintvolatile(object o, long offset); /** volatile version of {@link #putint(object, long, int)} */
public native void putintvolatile(object o, long offset, int x); /** volatile version of {@link #getboolean(object, long)} */
public native boolean getbooleanvolatile(object o, long offset); /** volatile version of {@link #putboolean(object, long, boolean)} */
public native void putbooleanvolatile(object o, long offset, boolean x); /** volatile version of {@link #getbyte(object, long)} */
public native byte getbytevolatile(object o, long offset); /** volatile version of {@link #putbyte(object, long, byte)} */
public native void putbytevolatile(object o, long offset, byte x); /** volatile version of {@link #getshort(object, long)} */
public native short getshortvolatile(object o, long offset); /** volatile version of {@link #putshort(object, long, short)} */
public native void putshortvolatile(object o, long offset, short x); /** volatile version of {@link #getchar(object, long)} */
public native char getcharvolatile(object o, long offset); /** volatile version of {@link #putchar(object, long, char)} */
public native void putcharvolatile(object o, long offset, char x); /** volatile version of {@link #getlong(object, long)} */
public native long getlongvolatile(object o, long offset); /** volatile version of {@link #putlong(object, long, long)} */
public native void putlongvolatile(object o, long offset, long x); /** volatile version of {@link #getfloat(object, long)} */
public native float getfloatvolatile(object o, long offset); /** volatile version of {@link #putfloat(object, long, float)} */
public native void putfloatvolatile(object o, long offset, float x); /** volatile version of {@link #getdouble(object, long)} */
public native double getdoublevolatile(object o, long offset); /** volatile version of {@link #putdouble(object, long, double)} */
public native void putdoublevolatile(object o, long offset, double x); /**
* version of {@link #putobjectvolatile(object, long, object)}
* that does not guarantee immediate visibility of the store to
* other threads. this method is generally only useful if the
* underlying field is a java volatile (or if an array cell, one
* that is otherwise only accessed using volatile accesses).
*/
public native void putorderedobject(object o, long offset, object x); /** ordered/lazy version of {@link #putintvolatile(object, long, int)} */
public native void putorderedint(object o, long offset, int x); /** ordered/lazy version of {@link #putlongvolatile(object, long, long)} */
public native void putorderedlong(object o, long offset, long x); /**
* unblock the given thread blocked on park, or, if it is
* not blocked, cause the subsequent call to park not to
* block. note: this operation is "unsafe" solely because the
* caller must somehow ensure that the thread has not been
* destroyed. nothing special is usually required to ensure this
* when called from java (in which there will ordinarily be a live
* reference to the thread) but this is not nearly-automatically
* so when calling from native code.
* @param thread the thread to unpark.
*
*/
public native void unpark(object thread); /**
* block current thread, returning when a balancing
* unpark occurs, or a balancing unpark has
* already occurred, or the thread is interrupted, or, if not
* absolute and time is not zero, the given time nanoseconds have
* elapsed, or if absolute, the given deadline in milliseconds
* since epoch has passed, or spuriously (i.e., returning for no
* "reason"). note: this operation is in the unsafe class only
* because unpark is, so it would be strange to place it
* elsewhere.
*/
public native void park(boolean isabsolute, long time); /**
* gets the load average in the system run queue assigned
* to the available processors averaged over various periods of time.
* this method retrieves the given nelem samples and
* assigns to the elements of the given loadavg array.
* the system imposes a maximum of 3 samples, representing
* averages over the last 1, 5, and 15 minutes, respectively.
*
* @params loadavg an array of double of size nelems
* @params nelems the number of samples to be retrieved and
* must be 1 to 3.
*
* @return the number of samples actually retrieved; or -1
* if the load average is unobtainable.
*/
public native int getloadaverage(double[] loadavg, int nelems); // the following contain cas-based java implementations used on
// platforms not supporting native instructions /**
* atomically adds the given value to the current value of a field
* or array element within the given object o
* at the given offset.
*
* @param o object/array to update the field/element in
* @param offset field/element offset
* @param delta the value to add
* @return the previous value
* @since 1.8
*/
public final int getandaddint(object o, long offset, int delta) {
int v;
do {
v = getintvolatile(o, offset);
} while (!compareandswapint(o, offset, v, v delta));
return v;
} /**
* atomically adds the given value to the current value of a field
* or array element within the given object o
* at the given offset.
*
* @param o object/array to update the field/element in
* @param offset field/element offset
* @param delta the value to add
* @return the previous value
* @since 1.8
*/
public final long getandaddlong(object o, long offset, long delta) {
long v;
do {
v = getlongvolatile(o, offset);
} while (!compareandswaplong(o, offset, v, v delta));
return v;
} /**
* atomically exchanges the given value with the current value of
* a field or array element within the given object o
* at the given offset.
*
* @param o object/array to update the field/element in
* @param offset field/element offset
* @param newvalue new value
* @return the previous value
* @since 1.8
*/
public final int getandsetint(object o, long offset, int newvalue) {
int v;
do {
v = getintvolatile(o, offset);
} while (!compareandswapint(o, offset, v, newvalue));
return v;
} /**
* atomically exchanges the given value with the current value of
* a field or array element within the given object o
* at the given offset.
*
* @param o object/array to update the field/element in
* @param offset field/element offset
* @param newvalue new value
* @return the previous value
* @since 1.8
*/
public final long getandsetlong(object o, long offset, long newvalue) {
long v;
do {
v = getlongvolatile(o, offset);
} while (!compareandswaplong(o, offset, v, newvalue));
return v;
} /**
* atomically exchanges the given reference value with the current
* reference value of a field or array element within the given
* object o at the given offset.
*
* @param o object/array to update the field/element in
* @param offset field/element offset
* @param newvalue new value
* @return the previous value
* @since 1.8
*/
public final object getandsetobject(object o, long offset, object newvalue) {
object v;
do {
v = getobjectvolatile(o, offset);
} while (!compareandswapobject(o, offset, v, newvalue));
return v;
} /**
* ensures lack of reordering of loads before the fence
* with loads or stores after the fence.
* @since 1.8
*/
public native void loadfence(); /**
* ensures lack of reordering of stores before the fence
* with loads or stores after the fence.
* @since 1.8
*/
public native void storefence(); /**
* ensures lack of reordering of loads or stores before the fence
* with loads or stores after the fence.
* @since 1.8
*/
public native void fullfence(); /**
* throws illegalaccesserror; for use by the vm.
* @since 1.8
*/
private static void throwillegalaccesserror() {
throw new illegalaccesserror();
} }

unsafe源码

参考:《java魔法类:unsafe应用解析》

java底层魔术类unsafe的相关教程结束。

网站地图