何时以及如何释放NIO直接缓冲区? [英] When and how are NIO direct buffers freed?

查看:143
本文介绍了何时以及如何释放NIO直接缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C库,需要临时缓冲区用于临时空间。我正在考虑将直接字节缓冲区的地址传递给它。

I have a C library that wants a temporary buffer for scratch space. I'm considering passing the address of a direct byte buffer to it.


  • 是否允许VM在最终释放之前重新定位缓冲区?
    在JNI帧消失后,本机库将保持指针。我的理解是无法缓存JNI本地对象引用,因为VM可能在GC期间重定位它们。这是否适用于缓冲区地址?

  • Is the VM ever allowed to relocate the buffer before it is ultimately freed? The native library will be holding on to the pointer after the JNI frame goes away. My understanding is that JNI local object references cannot be cached because the VM may relocate them during GC. Does this apply to the buffer address?

我知道如果我在Java中分配缓冲区然后让缓冲区对象熄灭,VM将释放缓冲区内存范围。如果我使用NewDirectByteBuffer在本机代码中创建一个新的缓冲区,它的职责是释放后备内存?

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. If I create a new buffer in native code using NewDirectByteBuffer, whose responsibility is it to free the backing memory?

如果我使用NewDirectByteBuffer在本机代码中创建一个新缓冲区并且直接缓冲区已经使用了一个地址,会发生什么?记忆会被双重释放吗?当引用它的最后一个缓冲区被垃圾收集时,VM引用会计算内存块并尝试释放它吗?

What happens if I create a new buffer in native code using NewDirectByteBuffer and an address already in use by a direct buffer? 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?

它不会重新定位它,因为直接缓冲区不是GC堆的一部分。

It won't relocate it, because the direct buffer is not part of the GC heap.


如果我使用NewDirectByteBuffer在本机
代码中创建一个新缓冲区,其
责任是释放
后备内存?

If I create a new buffer in native code using NewDirectByteBuffer, whose responsibility is it to free the backing memory?

释放它是你的(本地代码)责任。 JVM无法知道用于分配该后备存储的方法(可以是malloc,可以是静态缓冲区等)。

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.)


如果我使用
NewDirectByteBuffer和直接缓冲区已经使用的地址
在本机代码中创建一个新缓冲区
会发生什么?

What happens if I create a new buffer in native code using NewDirectByteBuffer and an address already in use by a direct buffer?

鉴于VM不会尝试释放其地址传递给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.

这篇关于何时以及如何释放NIO直接缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆