java DirectBuffer,释放
我分配了一个直接缓冲区:
ByteBuffer directBuffer = ByteBuffer.allocateDirect(1024);
我读过:
Deallocating Direct Buffer Native Memory in Java for JOGL
但它没有直接回答
总结一下:
- GC将在启动GC时释放
directbuffer
,而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++中的智能指针,不是吗?p>
共 (0) 个答案