在Java中访问内存的最佳方法是什么,类似于mmap? [英] What is the best way to access memory in Java, similar to mmap?

查看:572
本文介绍了在Java中访问内存的最佳方法是什么,类似于mmap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on a Java application that needs to communicate with a C application. The C application uses shared memory and mmap to communicate, and I need the Java application to have access to the same memory.

我首次尝试使用JNI调用来检索数据从共享内存中,但每个JNI调用的开销都会导致性能下降,因此我想要一种在Java中访问该内存并在Java端进行数据检索的方法。

My first attempt involved using JNI calls to retrieve data from the shared memory, but the overhead of each JNI call killed performance, so I'd like a way to get access to that memory in Java and do the data retrieval on the Java side.

我的想法是我需要做以下事情:

The idea I have is that I'd need do the following:


  1. 使用一个JNI调用来获取我需要附加到的共享内存位置的位置

  2. 创建一个新的FileChannel()

  3. 使用该FileChannel使用map()创建MappedByteBuffer

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

Is this the best way to do this? Also, I'm not sure how to actually create the FileChannel to point at the correct memory location.

推荐答案

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

Look into using ByteBuffer.allocateDirect. Apparently these buffers can be passed over the JNI layer to native code which can access the memory directly.

参见此页面(引用如下)提示。

See this page (quoted below) for hints.


现在,JNI代码不仅可以发现在Java端使用ByteBuffer.allocateDirect()创建的缓冲区内的本机内存空间的地址,而且可以分配自己的内存(例如,malloc()然后回调到JVM以将该内存空间包装在一个新的ByteBuffer对象中(执行此操作的JNI方法是NewDirectByteBuffer())。

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中访问内存的最佳方法是什么,类似于mmap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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