java.misc.Unsafe底层操作类简单示例

通过java.misc.Unsafe可以直接操作内存数据,因此可以达到加速的效果,对时间要求较高的程序可以利用这个包

import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.Arrays;

import sun.misc.Unsafe;

public class Testunsafe {
	private static long byteArrayBaseoffset;
	private static long mbase;
	private static long moffset;
	private static int first = 10;
	private int second = 10;
	
	public static void main(String[]args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, IOException{
		Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
		theUnsafe.setAccessible(true);
		Unsafe unsafeinstance = (Unsafe)theUnsafe.get(null);
		System.out.println(unsafeinstance);
		
		int[] data = new int[10];
		int[] tmp = new int[10];
		System.out.println(Arrays.toString(data));
		byteArrayBaseoffset = unsafeinstance.arrayBaseOffset(int[].class);
		
		System.out.println(byteArrayBaseoffset);
		unsafeinstance.putInt(tmp, byteArrayBaseoffset, (int)1);
		System.out.println(Arrays.toString(tmp));
		unsafeinstance.putInt(tmp, byteArrayBaseoffset+4, (int)5);
		System.out.println(Arrays.toString(tmp));
		
		byte[] data2 = new byte[10];
		System.out.println(Arrays.toString(data2));
		
		System.out.println(byteArrayBaseoffset);
		unsafeinstance.putByte(data2, byteArrayBaseoffset, (byte)1);
		System.out.println(Arrays.toString(data2));
		unsafeinstance.putByte(data2, byteArrayBaseoffset+1, (byte)5);
		System.out.println(Arrays.toString(data2));
		
		Field firstfield = Testunsafe.class.getDeclaredField("first");
		System.out.println("Location of first:" + unsafeinstance.staticFieldOffset(firstfield));
		Field secondfield = Testunsafe.class.getDeclaredField("second");
		System.out.println("Location of second:" + unsafeinstance.objectFieldOffset(secondfield));
		
		ByteBuffer dbuf = ByteBuffer.allocateDirect(10);
		byte t = '0';
		dbuf.put(t);
		dbuf.put(t);
		Field dbaddressField = Buffer.class.getDeclaredField("address");
		dbaddressField.setAccessible(true);
		mbase = (long)dbaddressField.get(dbuf);
		moffset = mbase;
		byte d = unsafeinstance.getByte(moffset);
		unsafeinstance.copyMemory(null, moffset, data2, byteArrayBaseoffset+2, data2.length);//将dbuf中内容复制到data2
		System.out.println(d);
		System.out.println(Arrays.toString(data2));
	}
}

上述最后的内存中复制过程中ByteBuffer dbuf必须调用ByteBuffer的allocateDirect方法,否则会出错。因此如果需要在类中包装此方法,可通过dbuf.isDirect()这样判断。再更进一步,如果应用在网络编程中,可能出现大端小端问题,应更进一步判断,dbuf.order() == ByteOrder.nativeOrder()?



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值