java - DirectBuffer、释放

标签 java garbage-collection direct-buffer

我分配了一个直接缓冲区:

ByteBuffer directBuffer = ByteBuffer.allocateDirect(1024);

我读过:

Deallocating Direct Buffer Native Memory in Java for JOGL

但它不直接回答。

总结一下:

  1. 当 GC 启动且 directbuffer 未被引用时,GC 会释放一个 directbuffer。在链接的帖子中写道:

When you know that a direct NIO buffer has become useless for you, you have to release its native memory by using its sun.misc.Cleaner (StaxMan is right) and call clean() (except with Apache Harmony), call free() (with Apache Harmony) or use a better public API to do that (maybe in Java >= 1.9, AutoCleaning that extends AutoCloseable?).

但我没有看到如何显式释放内存块。好的,存在一个 sun.misc.Cleaner ,还有什么?:

Cleaner c = new Cleaner()

  • 使用 DirectBuffer 而不是 Unsafe.allocateMemory 的目的是什么。


  • This solution (in this JEP, still a draft, probably not available in Java 1.9) is very promising, we won't need to use non public APIs.

    public long memory(long index) {
        // The scope where the memory region is available
        // Implements AutoClosable but `close` can be called manually as well
        try (Scope scope = new NativeScope()) {
            // Allocate the actual memory area, in this case in the style of a "long-array"
            Pointer<Long> ptr = scope.allocate(
                        NativeLibrary.createLayout(long.class), numElements);
    
            // Get the reference to a certain element
            Reference<Long> ref = ptr.offset(index).deref();
    
            // Set a value to this element through the reference
            ref.set(Long.MAX_VALUE);
    
            // Read the value of an element
            return ref.get();
        }
    }
    

    它看起来像 C++ 中的智能指针,不是吗?

    最佳答案

    but I didn't see how to explicitly release of memory chunk.

    目前你不能在java中这样做,因为它不安全。它可能会导致释放后使用错误。 确保安全的方法,例如虚拟内存操作或安全点体操很困难,可能会降低一些性能,或者可能无法在所有平台上工作。

    这并非不可能,但需要大量工作。请参阅JDK-4724038 、多年来积累的提案的副本和链接邮件列表。

    What is the purpose of using DirectBuffer instead of Unsafe.allocateMemory.

    安全访问稳定的内存位置,这些位置可以传递给 native 代码,无需复制,也无需对象固定(热点不支持此操作)。

    关于java - DirectBuffer、释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46625511/

    相关文章:

    java - Java 中可以手动删除对象吗?

    java - 在java中释放直接缓冲区以及可能的陷阱

    java - 无法从字符串转换为字节数组

    java - 使用 Java 私有(private)方法(JDK 类)安全吗?

    java - 在 JEditorPane 或 JTextPane 中设置 HTML 样式

    Java - 什么时候释放直接缓冲区?

    java - 浏览文件夹以加载类

    java - Java中的突发内存使用

    .net - "Memory Pressure"是什么意思?