java直接内存的读写操作

前言

在之前已经讲过了一些关于直接内存的知识,相对于的就会去思考,直接内存是怎么去使用的。
首先说明下,一般不会直接这样去用直接内存,这个例子只能当做一个例子去使用,netty里面有许多非常经典的使用方式,可以参考下。

代码

这里没有什么好说的先上代码吧。
public class BufferTest4 {

    private static final int BUFFER = 10 * 1024 * 1024;//10m

    //直接分配本地内存空间
    private static ByteBuffer byteBuffer = ByteBuffer.allocateDirect(BUFFER);

    public static void main(String[] args) throws IOException {

        Scanner scanner = new Scanner(System.in);
        System.out.println("请求指示:");
        scanner.next();
        List<TestObj> bigObj = new ArrayList<TestObj>();
        for (int n = 0; n < 600000; n++) {
            bigObj.add(new TestObj(n));
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Hessian2Output output = new Hessian2Output(bos);
        output.writeObject(bigObj);
        output.flush();
        byte[] date = bos.toByteArray();
        bos.close();
        byteBuffer.put(date);

        System.out.println("对象存入到直接内存!");

        scanner.next();
        byteBuffer.flip();
        byte[] b = new byte[byteBuffer.limit()];
        int i = 0;
        while (byteBuffer.hasRemaining()) {

            b[i] = byteBuffer.get();
            i++;
        }

        ByteArrayInputStream bis = new ByteArrayInputStream(b);
        Hessian2Input input = new Hessian2Input(bis);
        List<TestObj> objRead = (List<TestObj>) input.readObject();

        System.out.println("读取直接内存内的对象!" + objRead);
        scanner.next();

        System.out.println("直接内存开始释放!");
        byteBuffer = null;
        System.gc();

        scanner.next();
    }
}

直接内存的申请这里就不多说,一般并且下我们会先将序列化好的对象放入到内存中

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        // Hessian2的序列化方式
        Hessian2Output output = new Hessian2Output(bos);
        output.writeObject(bigObj);
        output.flush();
        byte[] date = bos.toByteArray();
        bos.close();
        //放入内存
        byteBuffer.put(date);
如果需要读取出来,就需要先将标志位反转,然后开始读取,最后还是需要反序列化
  
      // 反转标志位
        byteBuffer.flip();
        byte[] b = new byte[byteBuffer.limit()];
        int i = 0;
        // 判断是否还有未读的
        while (byteBuffer.hasRemaining()) {
            b[i] = byteBuffer.get();
            i++;
        }
        // 反序列化
        ByteArrayInputStream bis = new ByteArrayInputStream(b);
        Hessian2Input input = new Hessian2Input(bis);
        List<TestObj> objRead = (List<TestObj>) input.readObject();

扩展说明

在上面的例子中,申请的内存是10m,如果生成的对象比申请的直接内存大会怎么样?可以将申请的内存改为3m,运行代码的时候直接报如下错误。

请求指示:
1
Exception in thread "main" java.nio.BufferOverflowException
    at java.nio.DirectByteBuffer.put(DirectByteBuffer.java:360)
    at java.nio.ByteBuffer.put(ByteBuffer.java:859)
为什么说,上面的例子不是一个确定的用法,上面的例子最后还是将用到了jvm里面的内存,并没有利用到直接内存的优点。不需要中系统内存复制到jvm内存中,这个才是直接内存的有点。
下面写一个例子测试下直接内存的读取
public class ByteBufferDemo1 {

    public static void main(String[] args) throws IOException {

        long start =  System.currentTimeMillis();
        String filepath = "/Users/*/Downloads/2.1.0.501.zip" //1g左右;
        FileInputStream fis = new FileInputStream(filepath);
        FileChannel fci = fis.getChannel();


        // 把刚读取的信息写到一个新的文件中
        String outfilepath = "/Users/*/code/2.1.0.501.zip";
        FileOutputStream fos = new FileOutputStream(outfilepath);
        FileChannel fco = fos.getChannel();


        // 使用allocateDirect,而不是allocate
        ByteBuffer buffer = ByteBuffer.allocateDirect(512*1024*1024);
        while (true) {
            buffer.clear();
            int r = fci.read(buffer);
            if (r == -1) break;
            buffer.flip();
            fco.write(buffer);
        }


        long end =  System.currentTimeMillis();


        System.out.println((end-start));
    }
}
使用 ByteBuffer.allocateDirect
第一次
1409
Process finished with exit code 0

第二次
1401
Process finished with exit code 0

第三次
1372
Process finished with exit code 0

使用ByteBuffer.allocate

第一次
2087
Process finished with exit code 0

第二次
2159
Process finished with exit code 0

第三次
2219
Process finished with exit code 0
稍微快一点。
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sinom21

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值