inter jvm communication [closed]

旧时模样 提交于 2019-11-27 19:55:38

Java NIO has support for memory-mapped files. If multiple JVMs memory-map the same file they can use it as shared memory.

Here is an example of memory mapping a file.

try {
int shmSize = 1024;
RandomAccessFile file = new RandomAccessFile("shm.raw","rw");

// inialize file size
if(file.length() < shmSize) {
  byte[] tmp = new byte[shmSize];
  file.write(tmp);
  file.seek(0); // seek back to start of file.
}

// memory-map file.
FileChannel ch = file.getChannel();
MappedByteBuffer shm = ch.map(FileChannel.MapMode.READ_WRITE, 0, shmSize);
ch.close(); // channel not needed anymore.
shm.load(); // force file into physical memory.

// now use the ByteBuffer's get/put/position methods to read/write the shared memory

} catch(Exception e) { e.printStackTrace(); }

On Linux you can create the shm.raw file in /dev/shm/ a memory based filesystem. This will help avoid any disk I/O.

For more details read this article Introduction to Memory-Mapped IO in Java

Also you will still need a way to syncronize read/writes to the shared memory. The sender JVM will need to signal the receiver JVM when a complete message has been written.

Using Java NIO's SocketChannel might be better for small messages since the receiver can be notified when a message is received. Shared memory will only really help when sending large messages.

For IPC between JVMs on different machines try JIPC

I would suggest you to take a look on Terracotta. I don't know if it will fit your requirements, because Terracotta's main goal is seamless scalability ("api" is just memory access), but it certainly has messaging integration module. It is opensource.

Cheers.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!