Fixing Random Crashes in JNI Code
(home)Do you have an application that uses JNI to provide a C/C++ interface to a Java library? Are you experiencing random crashes and segmentation faults in seemingly unrelated parts of said application? Have you pulled out all your hair while trying to figure out what the problem is?
The good news is that I may have a solution for you!
I was recently testing Portico with a large, widely deployed C++ application. The Portico C++ interface uses JNI to wrap the core Java library. Other applications then link against this interface and use the library to do whatever it is they need to do.
When testing this large application I noticed a lot of crashes in code that was totally unrelated to Portico. For the life of me I couldn’t figure out what the problem was. This was made even more frustrating by the lack of any help from Google. Eventually however, I stumbled across this post, which discusses something that sounded quite familiar.
My current understanding is that the JNI uses various signals to complete its work, and that if you have an application that puts its own signal handlers in place, they will replace the JNI handlers thus causing problems. You can try starting the JVM with -Xrs to make it reduce signal use, but this doesn’t entirely eliminate it, potentially leaving you with the problem.
Fortunately, Sun ship a signal handler chaining library with the JVM. When I linked against that (no code change required!) everything started to work happily! The libjsig.so library is in the same directory as libjvm.so which you need to link against anyway, so the grand solution is to just as a -ljsig to your compile/linking command. Talk about a simple solution to an incredibly frustrating problem. For full details see the article above.
I’ve decided to post this little discovery here in the hope that Google finds it and saves someone else a whole bunch of pain. Never say I don’t do anything for you Internet.
Useful resources:
If JNI based application is crashing, check signal handling!
Revelations on Java signal handling and termination
