I have the following situation:
I have 2 JVM processes (really 2 java
processes running separately, not 2 threads) running on a local machine. Let's call them ProcessA
an ProcessB
.
I want them to communicate (exchange data) with one another (e.g. ProcessA
sends a message to ProcessB
to do something).
Now, I work around this issue by writing a temporary file and these process periodically scan this file to get message. I think this solution is not so good.
What would be a better alternative to achieve what I want?
One java app can run the other via Runtime. exec() and control it (communicate) using the input stream. One could use JNI and a OS specific feature like named pipes or shared memory. You can also use java RMI to communicate between two applications, one calling methods of the other.
The client program connects to the server with a socket. Once the socket connection is established, either program can send or receive information. Another option is to use stream files for communication between programs. To do this, use the System.in, System.
I've added a library on github called Mappedbus (http://github.com/caplogic/mappedbus) which enable two (or many more) Java processes/JVMs to communicate by exchanging messages. The library uses a memory mapped file and makes use of fetch-and-add and volatile read/writes to synchronize the different readers and writers. I've measured the throughput between two processes using this library to 40 million messages/s with an average latency of 25 ns for reading/writing a single message.
Multiple options for IPC:
Without more details, a bare-bone network-based IPC approach seems the best, as it's the:
That being said, based on your example (simply requesting the other process to do an action), JMX could also be good enough for you.
What you are looking for is inter-process communication
. Java provides a simple IPC framework in the form of Java RMI API. There are several other mechanisms for inter-process communication such as pipes, sockets, message queues (these are all concepts, obviously, so there are frameworks that implement these).
I think in your case Java RMI or a simple custom socket implementation should suffice.
Sockets with DataInput(Output)Stream, to send java objects back and forth. This is easier than using disk file, and much easier than Netty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With