美文网首页
一、NIO 概述

一、NIO 概述

作者: wyh001 | 来源:发表于2022-06-16 12:46 被阅读0次

Jdk Nio Api 文档地址:https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/nio/package-summary.html

  1. 核心类和接口
  1. ByteBuffer
    基本类型数据的容器,对数组的包装
    直接内存和堆内存
    直接内存的分配和回收
public static void buffer() {
    final ByteBuffer byteBuffer = ByteBuffer.allocateDirect(32);
}

java.nio.DirectByteBuffer

DirectByteBuffer(int cap) {
    // ...
    // 累计申请直接内存大小,判断否达到最大值
    Bits.reserveMemory(size, cap);
    long base = 0;
    try {
        // 分配直接内存,返回内存首地址
        base = UNSAFE.allocateMemory(size);
    } catch (OutOfMemoryError x) {
        // 减少累计直接内存大小统计
        Bits.unreserveMemory(size, cap);
        throw x;
    }

    // 通过 PhantomReference 在该对象 GC 时,释放直接内存
    cleaner = Cleaner.create(this, new Deallocator(base, size, cap));
}

Deallocator

public void run() {
    // ...
    // 释放直接内存
    UNSAFE.freeMemory(address);
    // 减少累计直接内存大小统计
    Bits.unreserveMemory(size, capacity);
}

相关文章

网友评论

      本文标题:一、NIO 概述

      本文链接:https://www.haomeiwen.com/subject/kxcqvrtx.html