【知识积累】深入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的类型

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

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

猜你喜欢

转载自blog.csdn.net/axin1240101543/article/details/117318603