srvnn
srvnn

Reputation: 75

JVM crashing on attachCurrentThread JNI callback invocation

Hope you are doing well.

I have a JNI implementation in C wherein a C function attach to current JVM thread and callback a Java method, which is actually crashing the JVM upon attachCurrentThread() function call. My implementation is based on the answer given in the link Keeping a global reference to the JNIEnv environment

Thread creation part which will listen for a socket connection to accept an event and inject the GetEvent function.

// create thread for reading from socket.
        pthread_attr_init(&plafParams->readThreadAttr);
        pthread_attr_setdetachstate(&plafParams->readThreadAttr, PTHREAD_CREATE_JOINABLE);
        pthread_attr_setstacksize(&plafParams->readThreadAttr, 16384);
        plafParams->eventThreadFlag = 2;
        if(pthread_create(&plafParams->hReadThread_p, &plafParams->readThreadAttr, ( void * ) plafIncomingPortReadThread, ( void * ) dlmsInstance))
        {

            plafFree(plafParams);
            return FAILURE;
        }

        //create thread to read from platform (to monitor wrapperRecv() process)
        pthread_attr_init(&plafParams->EventthreadAttr);
        pthread_attr_setdetachstate(&plafParams->EventthreadAttr, PTHREAD_CREATE_JOINABLE);
        pthread_attr_setstacksize(&plafParams->EventthreadAttr, 16384);

        if( pthread_create(&plafParams->EventThreadHandle_p, &plafParams->EventthreadAttr, ( void * ) IncomingPortEventReadHandling, ( void * ) dlmsInstance))
        {
            pthread_attr_destroy(&plafParams->readThreadAttr);
            plafParams->eventThreadFlag = 0;
            return FAILURE;
        }



static JavaVM *jvm;

// Caching the JVM on JVM OnLoad
jint JNI_OnLoad(JavaVM* vm, void* reserved) 
{
    JNIEnv* jenv;
    version = (*vm)->GetEnv(vm, (void **) &jenv, JNI_VERSION_1_6);
    jvm = vm;
    printf("\n jvm = %d \n",rs);
    if(rs == JNI_OK) {
        printf("\n JNI_OK \n");
    }
}

Callback function

void GetEvent(unsigned char *msg)
    {

        printf("\n Processing event data \n");
        JNIEnv *env;

        printf("\n Before attaching JVM thread \n");
        jint rs = (*jvm)->AttachCurrentThread(jvm, &env, NULL); // JVM crashes here, tried with jint rs = (*jvm)->AttachCurrentThread(jvm, (void **) &env, NULL), nothing helps
        printf("\n After attaching JVM thread \n");

    }

Upon execution of GetEvent() on receiving a event, my JVM crashes on AttachCurrentThread() function call. Could someone help me to identify the problem? Thanks in advance and any suggestions would be greatly appreciated.

regards,

Saravanan G

Upvotes: 1

Views: 3520

Answers (1)

Geki
Geki

Reputation: 247

I guess your Thread can already be attached to the VM, so AttachCurrentThread is not needed. Maybe you just need to check the thread state like this:

How to obtain JNI interface pointer (JNIEnv *) for asynchronous calls

Upvotes: 0

Related Questions