Unexpected Java memory stream

I am trying to create an API to allow my Java application to interact with a proprietary messaging environment between processes. Messages exist in unmanaged memory. As soon as I received the message, I want to have a stream for reading and writing to the message. Although I understand the basics of JNI, I'm struggling to figure out which standard Java classes can help create a thread in unmanaged memory.

I would appreciate any pointers

Hi

+1
java jni
source share
2 answers

I would use direct ByteBuffer. You can change the address and limit through JNI. Once you do this, you can read or change anything in this ByteBuffer, and it will change to an โ€œunmanagedโ€ size.

ByteBuffer supports small and large endian and reads and writes all primitive types.


An unusual way to do this is to use the Unsafe class. It supports access to primitives in an arbitrary memory area (just like a pointer). In many cases, it also boils down to one machine code instruction. Unsafe is not safe or portable, and if you can use ByteBuffer, this is the best choice.

+4
source share

The JNI API has a NewDirectByteBuffer method, which is declared as:

jobject NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity); 

What he does is take the memory region described by void* , pointing to the top and length, and create a ByteBuffer wrap. This is not a copy; changes in the buffer will change the data in the memory area.

ByteBuffer has a fairly rich API. There is no standard way to create an InputStream that reads or an OutputStream that writes to one, but such things would be very easy to write.

+2
source share

All Articles