Java直接内存读写

        在Hotspot JVM上,我们能够直接对内存进行读写操作。该类的allocateMemory方法用于申请分配内存,putAddress和getAddress方法用于对直接内存进行读写。

        下面将通过sun.misc.Unsafe演示直接读写内存的例子。

        注意:这只是一个例子,只是用来验证通过sun.misc.Unsafe来实现直接读写内存的可能性。但是,这样做并没有安全保证,而且稍微有点疏忽将可能导致JVM崩溃。

        Unsafe类的三个方法:allocateMemory,putAddress和getAddress如下:

1. long allocateMemory(long bytes)
        申请分配内存
2. long getAddress(long address) 和void putAddress(long address, long x)
        对直接内存进行读写

3.putByte、getByte方法,这两个方法deprecated了

        因为Unsafe这个类的访问是受限的,只有rt.jar中的类才能使用Unsafe的功能,它的构造方法是私有的,所以,我们不能通过new来创建实例。但是,可以通过反射的方法来获取Unsafe实例。

实例一:

package my.memory;

import java.lang.reflect.Field;

import sun.misc.Unsafe;

public class DirectMemoryAccess {

    public static void main(String[] args) {

        /*
         * Unsafe的构造函数是私有的,不能通过new来获得实例。
         * 
         *  通过反射来获取
         */
        Unsafe unsafe = null;
        Field field = null;
        try {
            field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
            /*
             * private static final Unsafe theUnsafe = new Unsafe();
             * 
             * 因为field的修饰符为 private static final,
             * 需要将setAccessible设置成true,否则会报java.lang.IllegalAccessException
             */
            field.setAccessible(true);
            unsafe = (Unsafe) field.get(null);
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        long oneHundred = 100;
        byte size = 1;

        /*
         * 调用allocateMemory分配内存
         */
        long memoryAddress = unsafe.allocateMemory(size);

        /*
         * 将100写入到内存中
         */
        unsafe.putAddress(memoryAddress, oneHundred);

        /*
         * 内存中读取数据 
         */
        long readValue = unsafe.getAddress(memoryAddress);

        System.out.println("Val : " + readValue);
    }
}

输出结果:

Val : 100

实例二:

package my.memory;

import java.lang.reflect.Field;
import java.util.Arrays;
import sun.misc.Unsafe;

public class DirectMemoryTest {
    
    private static int byteArrayBaseOffset;

    public static void main(String[] args) throws SecurityException, NoSuchFieldException, IllegalArgumentException,
            IllegalAccessException {
        
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        Unsafe UNSAFE = (Unsafe) theUnsafe.get(null);
        System.out.println(UNSAFE);

        byte[] data = new byte[10];
        System.out.println(Arrays.toString(data));
        byteArrayBaseOffset = UNSAFE.arrayBaseOffset(byte[].class);

        System.out.println("byteArrayBaseOffset:" + byteArrayBaseOffset);
        UNSAFE.putByte(data, byteArrayBaseOffset, (byte) 1);
        UNSAFE.putByte(data, byteArrayBaseOffset + 5, (byte) 5);
        
        System.out.println(Arrays.toString(data));
    }
}

运行结果:

sun.misc.Unsafe@de6ced
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
byteArrayBaseOffset:12
[1, 0, 0, 0, 0, 5, 0, 0, 0, 0]

实例三:

package my.memory;

import java.lang.reflect.Field;

import sun.misc.Unsafe;

public class SuperArray {
    
    private final static int BYTE = 1;    
    private long size;    
    private long address;    
             
    public SuperArray(long size) {    
        this.size = size;    
        //得到分配内存的起始地址    
        address = getUnsafe().allocateMemory(size * BYTE);    
    }    
    
    public void set(long i, byte value) {    
        getUnsafe().putByte(address + i * BYTE, value);    
    }    
    public int get(long idx) {    
        return getUnsafe().getByte(address + idx * BYTE);    
    }    
    public long size() {    
        return size;    
    }
    
    private static Unsafe getUnsafe() {
        Unsafe unsafe = null;
        Field field = null;
        try {
            field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
            /*
             * private static final Unsafe theUnsafe = new Unsafe();
             * 因为field的修饰符为 private static final,
             * 需要将setAccessible设置成true,否则会报java.lang.IllegalAccessException
             */
            field.setAccessible(true);
            unsafe = (Unsafe) field.get(null);
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return unsafe;
    }
    
    public static void main(String[] args) {
        int sum = 0;
        long SUPER_SIZE = (long)Integer.MAX_VALUE * 2;    
        SuperArray array = new SuperArray(SUPER_SIZE);    
        System.out.println("Array size:" + array.size()); // 4294967294    
        for (int i = 1; i <= 100; i++) {    
            array.set((long)i, (byte)3);    
            sum += array.get((long)i);    
        }    
        System.out.println("Sum of 100 elements:" + sum);  // 300
    }
}

运行结果:

Array size:4294967294
Sum of 100 elements:300

参考文章:

http://mouselearnjava.iteye.com/blog/1922390

http://tech.ddvip.com/2014-06/1403069715211221_2.html

PS:Unsafe的源代码,请参考下面的链接
http://www.docjar.com/html/api/sun/misc/Unsafe.java.html

猜你喜欢

转载自bijian1013.iteye.com/blog/2232847