inter jvm communication [closed]

蹲街弑〆低调 提交于 2019-11-26 20:03:29

问题


I am looking for an inter-process communication library in Java. I am looking to send small messages between JVMs and would like to do it using shared memory if I could.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/810212/inter-jvm-communication

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