1

All,

I'm having a hard time with some C++ JNI code. I have a long-running thread that handles pushing stuff from other parts of our system into the Java component.

Here's my code... the thread is "HandleUpdateNotification", and you can see I call a function to get necessary java references...

static void getJavaStuff(JavaVM*& jvmp, JNIEnv*& env){
    jint nSize =1;
    jint nVMs;
    jint nStatus = JNI_GetCreatedJavaVMs(&jvmp, nSize, &nVms);

    if(nStatus == 0){
      nStatus = jvmp->AttachCurrentThread((void**) &env, NULL);
      if(nStatus != 0){
          //throw error
      }
    }
}

static int HandleUpdateNotification(void *param)
{
   JavaVM* jvmp = NULL;
   JNIEnv *env = NULL;
   getJavaStuff(jvmp, env);

  while(true){
      //why would env be null here?
      if(env == NULL)
          getJavaStuff(jvmp, env);


      //do stuff with env pointer as I get stuff from other parts 
      //of my system, however I never set env
  }
  jvmp->DetachCurrentThread();
  return 0;
}

As you can see, I have a check in my loop to see if env has been set to NULL. That is because I found after running for several hours, env would all of the sudden get set to NULL, which caused segfaults when I tried using it later in the thread (referencing a null pointer) and would crash the VM. So, I added the check and would re-aquire everything. The problem is that hasn't fixed it... Now, I get a new pointer, but it's bogus... the program still segfaults and when I analyze the core file I see that indeed I cannot access the *env pointer.

Has anyone experienced anything like this and know how to combat it?

Platform is: java version "1.7.0_25" OpenJDK Runtime Environment (IcedTea 2.3.10) (7u25-2.3.10-1ubuntu0.12.04.2) OpenJDK Client VM (build 23.7-b01, mixed mode, sharing)

longofest
  • 616
  • 5
  • 16
  • 4
    Sounds like memory corruption (e.g. from a buffer overflow in your code somewhere). – user253751 Jun 03 '15 at 23:40
  • C and C++ are different languages. Your code a pretty C-like, but use of references makes it C++. – John Bollinger Jun 04 '15 at 02:45
  • Thanks John. It's C++ but in some legacy stuff that is from a C world, so it does take on C characteristics. I will clarify. – longofest Jun 05 '15 at 03:35
  • Once you've got your memory corruption fixed up, you should ensure that you properly manage your [thread attach/detach](http://stackoverflow.com/questions/9642506/jni-attach-detach-thread-memory-management/9647567#9647567). – technomage Jun 05 '15 at 13:28
  • @immibis it was memory corruption. Thank you. – longofest Jun 09 '15 at 12:57

0 Answers0