1

I need to call a RPC client which is implemented in C from a Java class.

The interaction is one way only(i.e) Java has to invoke specific functions in C, while C need not return anything to the calling Java code.

Can someone explain me the pros & cons in using either of the types (JNI/Runtime.exec)?? and which is the best option for my case?

Skilldrick
  • 69,215
  • 34
  • 177
  • 229
Pravin
  • 21
  • 1
  • 3

1 Answers1

1

Runtime.exec() will launch a separate process for each call. Your Java caller needs to consume the output of each process.

JNI would require a native, dynamically linked library. Depending on your operating system, you may need to explicitly export functions. You would define a Java class with "native" methods, generate a C header/stub file with javah, and implement the native methods by calling your C client functions.

Runtime.exec() probably consumes the most resources. I personally would use an in-process call to native code.

Instead of JNI, consider using JNA, which makes it easy to call C functions from Java without an ad hoc native glue layer. Your C functions would need to be in a native, dynamically linked library. In Java, you declare their signatures, load the library, and call the functions.

For Windows DLLs, be aware that you need to export functions for them to be available from outside the DLL.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
  • Hi Andy, could you explain more on speed, memory and system stability? Any opinion is also welcome if you have no tested metrics. – saurabheights Jan 12 '17 at 10:29
  • 1
    @saurabheights - I suspect, but have not tested on any of multiple platforms, that launching a new process costs more in time and space than calling a native method in an existing process. The former would need to do much of what the latter does, plus create and destroy a new process -- for each call. This could be ameliorated by creating a child process *once*, and piping commands to it. But it can be a simpler architecture just to use one process that uses JNA or JNI. See also [this answer](http://stackoverflow.com/questions/7699020/what-makes-jni-calls-slow/7809300#7809300). – Andy Thomas Jan 12 '17 at 21:43
  • Thank you so much and the shared answer is great, as well as the IBM article with it. +1. :) – saurabheights Jan 13 '17 at 05:15