RandomAccessFile rac = new RandomAccessFile("<some file name>", "rw");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.
FileChannel channel = rac.getChannel();
MappedByteBuffer buf = channel.map(MapMode.READ_WRITE, 0, 1024);
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.
here is a more complete example. link is not working
ReplyDelete