Unsafe类通过JNI的方式访问本地的C++实现库从而使java具有了直接操作内存空间的能力,Unsafe提供了硬件级别的原子性操作
objectFieldOffset()方法用于获取某个字段相对Java对象的“起始地址”的偏移量
unsafe.compareAndSwapInt这个方法,这个方法有四个参数,其中第一个参数为需要改变的对象,第二个为偏移量(即之前求出来的valueOffset的值),第三个参数为期待的值,第四个为更新后的值。
public class UnsafeTest1 {
private static Unsafe unsafe;
@Before
public void before(){
try {
// 注意:Unsafe的对象不能直接new,这里通过反射去获取Unsafe里面的私有成员变量theUnsafe
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (Unsafe)field.get(null);
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取对象字段或静态属性的内存地址偏移量
@Test
public void testGetFieldOffset() throws NoSuchFieldException, IllegalAccessException {
//获取字段偏移量
long address = unsafe.objectFieldOffset(People.class.getDeclaredField("name"));
System.out.println("实例变量name属性的偏移量:"+address);
//获取静态字段偏移量
long staticAddress = unsafe.staticFieldOffset(People.class.getDeclaredField("info"));
System.out.println("静态变量info属性的偏移量:"+staticAddress);
}
// 内存操作,包括内存的分配,释放,复制
@Test
public void testMemoryOperate() throws NoSuchFieldException, IllegalAccessException {
//分配内存
long address = unsafe.allocateMemory(4);
System.out.println(address);
//扩展内存
long newAddress = unsafe.reallocateMemory(address, 8);
System.out.println(newAddress);
//释放内存
unsafe.freeMemory(newAddress);
}
// 通过操作内存从一个给定的java变量获取或设置值
@Test
public void testGetAndPutInt() throws NoSuchFieldException, IllegalAccessException {
People people = new People("liming",16);
//通过objectFieldOffset方法获取学生年龄在内存中的偏移量
long offset = unsafe.objectFieldOffset(People.class.getDeclaredField("age"));
System.out.println("获取学生年龄在内存中的偏移量:"+offset);
//通过操作内存的方式获取学生年龄
int anInt = unsafe.getInt(people, offset);
System.out.println("获取学生年龄在内存中的值:"+anInt);
System.out.println("获取学生年龄值:"+people.getAge());
//通过操作内存的方式修改学生年龄
unsafe.putInt(people,offset,30);
System.out.println("通过unsafe修改后的值:"+people.getAge());
}
@Test
public void testGetAndPutObject() throws NoSuchFieldException, IllegalAccessException {
People people = new People("liming",16);
//通过objectFieldOffset方法获取学生姓名在内存中的偏移量
long offset = unsafe.objectFieldOffset(People.class.getDeclaredField("name"));
//获取对象属性
System.out.println(unsafe.getObject(people,offset));
System.out.println(people.getName());
//修改对象属性
unsafe.putObject(people,offset,"xiahua");
System.out.println(people.getName());
}
// 通过操作内存从一个内存地址获取或设置值
@Test
public void testGetAndPutInt2() throws NoSuchFieldException, IllegalAccessException {
//通过allocateMemory方法分配一个8具有8个字节的内存空间
long address = unsafe.allocateMemory(8);
//给指定的内存空间写入一个整型值
unsafe.putInt(address,60);
//获取内存空间的值
System.out.println(unsafe.getInt(address));
//重新分配内存,扩大到16字节
final long newAddress = unsafe.reallocateMemory(address, 16);
unsafe.putInt(newAddress,100);
System.out.println(unsafe.getInt(newAddress));
//回收分配的内存空间
unsafe.freeMemory(newAddress);
}
// 通过操作内存从一个给定的变量获取或设置一个具有volatile语义的值
@Test
public void testGetAndPutIntVolatile() throws NoSuchFieldException, IllegalAccessException {
long offset = unsafe.objectFieldOffset(People.class.getDeclaredField("age"));
//设置学生的年龄,使用volatile语义,设置后立马更新到内存对其他线程可见。
unsafe.putIntVolatile(People.class,offset,32);
System.out.println(unsafe.getIntVolatile(People.class,offset));
}
// 惰性设值,设值后内存不能保证立即对其他线程可见,并且变量和后序内存可以重排序
@Test
public void testPutIntVolatileLazy() throws NoSuchFieldException, IllegalAccessException {
long offset = unsafe.objectFieldOffset(People.class.getDeclaredField("age"));
unsafe.putOrderedInt(People.class,offset,100);
System.out.println(unsafe.getIntVolatile(People.class,offset));
}
// 通过操作内存获取或设置数组元素值
@Test
public void testArrayOperate() throws NoSuchFieldException, IllegalAccessException {
int[] array = new int[]{1,5,8,9,6,4,7};
//获取数组中第一个元素在内存的偏移地址
int offset = unsafe.arrayBaseOffset(array.getClass());
//获取数组增量元素在内存中的地址
int indexScale = unsafe.arrayIndexScale(array.getClass());
//通过操作内存地址获取数组的第一个元素
System.out.println(unsafe.getInt(array,offset));
//通过操作内存修改数组的第一个元素
unsafe.putInt(array,offset,3);
System.out.println(unsafe.getInt(array,offset));
//通过操作内存获取数组的第三个元素,arrayBaseOffset和arrayIndexScale共同使用,就可以获得任意一个数组元素在内存的地址
System.out.println(unsafe.getInt(array,indexScale*2+offset));
//通过循环遍历数组元素
for (int i = 0; i < array.length; i++) {
System.out.print(unsafe.getInt(array,i*indexScale+offset) + " ");
}
}
@Test
public void testGetAndPutAddress() throws NoSuchFieldException, IllegalAccessException {
//通过allocateMemory方法分配一个8具有8个字节的内存空间
long address = unsafe.allocateMemory(8);
//给这个内存中存放一个本地指针
unsafe.putAddress(address,200);
//获取指定内存地址的指针
System.out.println(unsafe.getAddress(address));
//打印通过putAddress存放的本地指针的大小
System.out.println(unsafe.addressSize());
//打印内存页面的大小,通常为4k,即4096 //关于内存页面不了解的可以看下操作系统相关的知识
System.out.println(unsafe.pageSize());
//释放内存
unsafe.freeMemory(address);
}
// 硬件级别的CAS操作
@Test
public void testCAS() throws NoSuchFieldException, IllegalAccessException {
long offset = unsafe.objectFieldOffset(People.class.getDeclaredField("age"));
unsafe.putInt(People.class,offset,25);
System.out.println(unsafe.getInt(People.class,offset));
//通过Unsafe提供的硬件级别的原子操作 CAS算法更新学生的年龄
unsafe.compareAndSwapInt(People.class,offset,24,35);
System.out.println(unsafe.getInt(People.class,offset));
unsafe.compareAndSwapInt(People.class,offset,25,35);
System.out.println(unsafe.getInt(People.class,offset));
}
// 线程的挂起与恢复
@Test
public void testParkAndUnPark() throws NoSuchFieldException, IllegalAccessException {
//写一个线程执行一个任务
Thread thread = new Thread(() -> System.out.println("hello"));
thread.start();
//线程恢复
unsafe.unpark(Thread.currentThread()); //如果不加这句,线程或一直处于阻塞状态
//线程挂起,直到unpark调用或者打断或者超时,线程恢复。
//isAbsolute设置是否为绝对时间,如果为true,则超时时间的单位为毫秒
//isAbsolute为false,time设置为0,就是一直阻塞,如果time不为0,则超时时间的单位为纳秒
unsafe.park(false,0);
}
// 从一个变量获取值并让它自动增加给定的值
@Test
public void testGetAndAddInt() throws NoSuchFieldException, IllegalAccessException {
final Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
Unsafe unsafe = (Unsafe) theUnsafe.get(null);
long offset = unsafe.objectFieldOffset(People.class.getDeclaredField("age"));
unsafe.putInt(People.class,offset,30);
System.out.println(unsafe.getAndAddInt(People.class,offset,3));
System.out.println(unsafe.getInt(People.class,offset));
}
// 从一个变量获取值并设置成另一个值
@Test
public void testGetAndSetInt() throws NoSuchFieldException, IllegalAccessException {
final Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
Unsafe unsafe = (Unsafe) theUnsafe.get(null);
long offset = unsafe.objectFieldOffset(People.class.getDeclaredField("age"));
unsafe.putInt(People.class,offset,30);
System.out.println(unsafe.getAndSetInt(People.class,offset,32));
System.out.println(unsafe.getInt(People.class,offset));
}
}
public class People {
private String name;
private int age;
public static String info;
static {
info = "hello world";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public People(String name, int age) {
this.name = name;
this.age = age;
}
public People() {
}
}