【知识积累】深入OpenJDK源码剖析直接内存

 一、堆内存和直接内存对比

package com.darren.service.memory;

import java.nio.ByteBuffer;

/**
 * <h3>netty</h3>
 * <p>直接内存</p>
 *
 * @author : Darren
 * @date : 2021年05月27日 08:25:23
 **/
public class DirectMemoryTest {

    public static void main(String[] args) {
        heapAccess();
        directAccess();
    }

    public static void heapAccess() {
        long startTime = System.currentTimeMillis();
        ByteBuffer buffer = ByteBuffer.allocate(1000);
        for (int i = 0; i < 100000; i++) {
            for (int j = 0; j < 200; j++) {
                buffer.putInt(j);
            }
            buffer.flip();

            for (int j = 0; j < 200; j++) {
                buffer.getInt();
            }
            buffer.clear();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("堆内存访问:" + (endTime - startTime) + "ms");
    }

    public static void directAccess(){
        long startTime = System.currentTimeMillis();
        ByteBuffer buffer = ByteBuffer.allocateDirect(1000);
        for (int i = 0; i < 100000; i++) {
            for (int j = 0; j < 200; j++) {
                buffer.putInt(j);
            }
            buffer.flip();

            for (int j = 0; j < 200; j++) {
                buffer.getInt();
            }
            buffer.clear();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("直接内存访问:" + (endTime - startTime) + "ms");
    }

}

调用Linux内核函数malloc分配物理内存,返回一个地址,然后将地址转换为java的类型

二、为什么所有的地方不直接使用直接内存?有哪些问题?

分配和销毁堆内存的速度更快,因为分配直接内存还需要调用系统函数来在系统上分配。
如果程序里面没有大量的数据传输拷贝,我们用堆内存。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值