What is the best way to implement C++/Java IPC for the following situation?
(Someone recently asked a similar question, but my requirements are more specific)
I have two programs -- one written in C++, the other in Java -- that need to communicate with each other. Both are running on the same machine.
The programs send messages to each other. Messages are typically short (less than a few hundred bytes), but could potentially be 100KB or more in size.
Messages do not need to be acknowledged (i.e., not a request/response model like HTTP). For example, the C++ program sends a message to the Java program, and the Java program may reply by sending a message to the C++ program at a later time -- and vice versa.
An ideal solution would have a) very low latency, b) no security hassles (user does not have to authorize ports to be opened etc.) and c) will be platform-agnostic.
My first thought was using sockets -- each program would act as a server to the other. Sockets have more overhead than other forms of IPC, and I don't know how the server would inform the client of the port number if I let the system auto-assign port numbers. I've also considered named pipes, but they are not supported (at least not consistently) across different platforms. JNI looks like an option, but can it cross process boundaries?
Any suggestions?
Thanks!
FOLLOW-UP QUESTIONS
Our experiments re- veal that shared memory provides the lowest latency and highest throughput, followed by kernel pipes and lastly, TCP/IP sockets.
The reasons why I (personally) prefer to write low latency systems in Java are the same as those that have made the language such a success over the last 25 years. Java is easy to write, compile, debug, and learn, and this means you can spend less time writing code and more time optimizing it for latency.
As a rule of thumb, when you convert Java to C++, the code is about 3x slower. This doesn't make sense at first, until you consider that code written in Java is "tuned to" the way Java code tends to be written, which is not at all how anyone who works in C++ would structure C++ code.
Java vs. C++ performance. In contrast, a program written in C++ gets compiled directly into machine code -- without an intermediary translation required at runtime. This is one reason why C++ programs tend to perform faster than those written in Java.
An alternative is using memory mapped files and keeping it portable by checking compiler settings if you are posix or not. POSIX OS's have mmap()
and in windows you would use CreateFileMapping()
In the boost library is a portable implementation for C++ and in java you should be able to use FileChannel()
.
This page does a good job of explaining how this can be used for IPC http://en.wikipedia.org/wiki/Memory-mapped_file
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