Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to access memory in Java, similar to mmap?

Tags:

java

memory

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.

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. Use one JNI call to get the location of the shared memory location I need to attach to
  2. Create a new FileChannel()
  3. Use that FileChannel to create a MappedByteBuffer using map()

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.

like image 994
Brian Avatar asked Jul 14 '09 13:07

Brian


1 Answers

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.

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

like image 63
Steve Reed Avatar answered Sep 19 '22 05:09

Steve Reed