2

I'm trying to decide if JNI is for our use case.

We have a library written in C++ that fetches data from Database/RPC using multiple threads, and we want to create a wrapper to let Java code be able to call it.

I'm not familiar with JNI, so I would like to know if C++ multithreading will still work properly in this case.

Thanks.

laike9m
  • 18,344
  • 20
  • 107
  • 140
  • Hey, I can't find an answer on the internet. If you want to close, mind help me refine the question? – laike9m Aug 27 '19 at 05:45
  • 1
    Multiple native threads are not a problem. But you cannot share the same `JNIEnv*` across threads (see e.g. [this](https://stackoverflow.com/questions/30026030/what-is-the-best-way-to-save-jnienv/30026231)). – Michael Aug 27 '19 at 05:51
  • Thanks Michael, we're not gonna do anything with the threads in Java code, just returning result. – laike9m Aug 27 '19 at 17:47
  • In theory this works fine, however, I have run into quite a few issues in practice. It is very hard to provide thread safety between native thread implementations and the JVM, and near impossible to debug resulting issues. I would strongly recommend keeping the concurrency on one side or the other, and in my experience, keeping it on the java side is a bit easier. – Alex Barker Aug 29 '19 at 20:00
  • @AlexBarker Thanks Alex. thread safety shouldn't be an issue for us, cause everything that get passed between C++ and Java code are some protobuf objects, there's no interaction across code other than that. So I guess in this case, it's ok to have concurrency on both side? – laike9m Aug 29 '19 at 20:15
  • @laike9m Possibly? No way to say for sure until you try it ;) – Alex Barker Aug 29 '19 at 20:51

1 Answers1

0

I don't see any major issues in neither direction. Unless you have something really specific.

Here you have sample that calls JNI code from multiple threads:

http://jnicookbook.owsiak.org/recipe-No-024/

Here you have sample that calls Java from multiple C threads:

http://jnicookbook.owsiak.org/recipe-no-027/

Oo.oO
  • 12,464
  • 3
  • 23
  • 45