Wednesday, March 11, 2009

Shared Memory Using MappedByteBuffer

Java developers can access shared memory using the NIO class MappedByteBuffer. Here is an example:
RandomAccessFile rac = new RandomAccessFile("<some file name>", "rw");
FileChannel channel = rac.getChannel();
MappedByteBuffer buf = channel.map(MapMode.READ_WRITE, 0, 1024);
This will create a shared memory segment with the name of the file passed to RandomAccessFile. The segment will start out with the contents of that file, if it exists. If the file does not exist, then it will be created.

The segment can be changed or read using the get/put methods defined by the ByteBuffer class. A different Java process that uses the same set of of calls will get the same shared memory: if they change their instance you will see the changes and vice versa. What's more, this also applies to non-java processes that use the same file name and memory mapped system calls.

I have tried this on Windows and Linux and I have also taken a look at the implementation code on java.net It appears that both platforms are using memory mapped files.

As an aside, "memory mapped files" are an approach to using shared memory that appear to have originated with Unix. Unix tries to make most things look like files, so representing shared memory that way is pretty consistent with the Unix philosophy.

For those who are interested, here is a more complete example.

1 comment:

  1. here is a more complete example. link is not working

    ReplyDelete