javac++objective-cjava-native-interface

C++/Java bindings : In which side should multi-threading be implemented?


I am implementing a C++ class called HttpDataStream in my library. I have to do the JNI bindings in order to use my library under Android, with the Objective-C bindings for iOS.

I need to create a dedicated HttpDataStream class in both Java and Objective-C, but I'm wondering if these classes would actually block the whole application until the download has finished.

For instance, let's call a read method from the HttpDataStream class on the "Android side" :

std::streamsize DataStreamJava::read(double value) {
  jmethodID m = jni->GetMethodID(j_dataStream_class_,
                                 "read", "(D)J");
  jni->CallLongMethod(j_dataStream_global_, m);
  return 0;
}

Let's say the read method would download the file and return the number of downloaded bytes. I'm currently thinking that, even if I use Threads and Runnables on the "Android side", the C++ library would actually block until the download is finished.

So I'm asking myself the following questions :


Solution

  • The answer depends on what do you expect from the multithreading:

    a) pipelining related actions on one side

    If your read() on Java side performs several dependend actions such as reading, interpreting or pre-proessing the data, and eventually rendering it, you could consider doing the multithreading on the java side.

    But however you do it on that side, your single call to the stream class' read() would return only when all the mutlithreaded actions on the java side are completed. So yes, in this case, the C++ code is stuck, waiting for the return.

    b) doing something unrelated

    So if you want your C++ code to do something else while the data is read, but not related to the aquired data, you should consider doing the multithreading on the C++ side (don't forget to attach the JNI environment to the new threads !).

    c) pipelining related actions on both sides

    But if you have to process some part of the aquired data by Java one the C++ side (for example, starting to display the data), then you could choose one of the following two approaches:

    The obsrever in java or in C++

    It depends on your choice and constraints related to the previous choices. Without knowing more, it's difficult to give you an objective and useful advice.