tags:

views:

931

answers:

2

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.

+2  A: 

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.

Artyom Sokolov
I looked at Terracotta but it is a very heavy solution for this problem. Thx
Javamann
A: 

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

Neopallium
For inter-machine I am using JGroups or Sockets from communication and for intra-JVM a Queue works. The hole in my communication component is inter-process on the same machine.
Javamann