java - 在 Java 中访问内存的最佳方式是什么,类似于 mmap?

标签 java memory

我正在开发一个需要与 C 应用程序通信的 Java 应用程序。 C 应用程序使用共享内存和 mmap 进行通信,我需要 Java 应用程序能够访问相同的内存。

我的第一次尝试涉及使用 JNI 调用从共享内存中检索数据,但是每个 JNI 调用的开销都会影响性能,所以我想要一种方法来访问 Java 中的内存并在Java 方面。

我的想法是我需要执行以下操作:

  1. 使用一个 JNI 调用来获取我需要附加到的共享内存位置的位置
  2. 创建一个新的 FileChannel()
  3. 使用该 FileChannel 通过 map() 创建一个 MappedByteBuffer

这是最好的方法吗?另外,我不确定如何实际创建 FileChannel 以指向正确的内存位置。

最佳答案

研究使用 ByteBuffer.allocateDirect。显然,这些缓冲区可以通过 JNI 层传递给可以直接访问内存的 native 代码。

this page (引用如下)以获取提示。

Now, not only can JNI code discover the address of the native memory space inside of a buffer created with ByteBuffer.allocateDirect() on the Java side, but it can allocate its own memory (with malloc(), for example) and then call back to the JVM to wrap that memory space in a new ByteBuffer object (the JNI method to do this is NewDirectByteBuffer()).

关于java - 在 Java 中访问内存的最佳方式是什么,类似于 mmap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1125534/

相关文章:

java - 地理位置检索背后的概念

java - 如何将 int[] 转换为 Integer[]?

java - Android Java - 如何嵌入在线视频

memory - 一旦被 bytes.Buffer 占用,就无法释放内存

haskell - foreign.Storable 中的大尺寸 Bool

java - 如何在Java Native Interface中获取Java "object"地址

c - 访问以字节形式存储在内存地址中的值

java - 重命名文件而不使用 renameTo() - Java

memory - 随着时间的推移,KTable/KStream 内存消耗

java - Android - 使用 LongClickListener 而不是 OnTouch 进​​行拖动?