简体   繁体   English

NIO直接缓冲区何时以及如何释放?

[英]When and how are NIO direct buffers freed?

I have a C library that wants a temporary buffer for scratch space. 我有一个C库,需要一个临时缓冲区来暂存空间。 I'm considering passing the address of a direct byte buffer to it. 我正在考虑将直接字节缓冲区的地址传递给它。

  • Is the VM ever allowed to relocate the buffer before it is ultimately freed? 是否允许VM在最终释放缓冲区之前重定位缓冲区? The native library will be holding on to the pointer after the JNI frame goes away. JNI框架消失后,本机库将保留指针。 My understanding is that JNI local object references cannot be cached because the VM may relocate them during GC. 我的理解是,无法缓存JNI本地对象引用,因为VM可能会在GC期间重新定位它们。 Does this apply to the buffer address? 这是否适用于缓冲区地址?

  • I understand that the VM will free buffer memory if I allocate a buffer in Java and then let the buffer object go out of scope. 我了解,如果我在Java中分配缓冲区,然后让缓冲区对象超出范围,则VM将释放缓冲区内存。 If I create a new buffer in native code using NewDirectByteBuffer, whose responsibility is it to free the backing memory? 如果我使用NewDirectByteBuffer在本机代码中创建一个新缓冲区,谁负责释放后备内存?

  • What happens if I create a new buffer in native code using NewDirectByteBuffer and an address already in use by a direct buffer? 如果我使用NewDirectByteBuffer和直接缓冲区已在使用的地址在本机代码中创建新缓冲区,会发生什么情况? Will the memory be doubly-freed? 内存会被释放吗? Will the VM reference count the memory block and attempt to free it when the last buffer referencing it is garbage collected? 当引用该内存的最后一个缓冲区被垃圾回收时,VM引用会计数该内存块并尝试释放它吗?

Is the VM ever allowed to relocate the buffer before it is ultimately freed? 是否允许VM在最终释放缓冲区之前重定位缓冲区?

It won't relocate it, because the direct buffer is not part of the GC heap. 它不会重定位,因为直接缓冲区不属于GC堆。

If I create a new buffer in native code using NewDirectByteBuffer, whose responsibility is it to free the backing memory? 如果我使用NewDirectByteBuffer在本机代码中创建一个新缓冲区,谁负责释放后备内存?

It's your (native code) responsibility to free it. 释放它是您(本机代码)的责任。 The JVM could not know what method was used to allocate that backing store (could be malloc'd, could be a static buffer, etc.) JVM不知道使用了什么方法来分配该后备存储(可以被malloc分配,可以是一个静态缓冲区,等等)。

What happens if I create a new buffer in native code using NewDirectByteBuffer and an address already in use by a direct buffer? 如果我使用NewDirectByteBuffer和直接缓冲区已在使用的地址在本机代码中创建新缓冲区,会发生什么情况?

Given that the VM won't attempt to free the memory whose address is passed to NewDirectByteBuffer, nothing will happen if you pass the same address twice. 由于VM不会尝试释放地址已传递给NewDirectByteBuffer的内存,因此,如果两次传递相同的地址,则不会发生任何事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM