How to handle thread in JNI
Hi,
I have a big problem in JNI and thread.
I use JNI to send the data to C++ application (MFC DLL), the code
att->setAtt(num) call the C++ Application. It use thread and socket.
I can run this code in VC Console. But when I put it in JNI (as below), it crashed, the debug showed ? the thread has existed ?.
I tried to add env->MonitorEnter(obj),JNI_GetCreatedJavaVMs(&jvm, size, &size) and jvm->AttachCurrentThread((void **)&env, NULL); before call C++ application.
But it still crash.
CApplication att= new CApplication;//C++ application
JavaVM *jvm;
JNIEXPORT void JNICALL
Java_NativeClient_setAtt(JNIEnv *env, jobject obj, jstring strNum)
{
const char *num = env->GetStringUTFChars(strNum, 0);
jint size = 100;
jint err = env->MonitorEnter(obj);
jint vm = JNI_GetCreatedJavaVMs(&jvm, size, &size);
jint th = jvm->AttachCurrentThread((void **)&env, NULL);
att->setAtt(num);
printf("%s", "the setAtt() ran already");
jvm->DetachCurrentThread();
env->MonitorExit(obj);
env->ReleaseStringUTFChars(strNum,num);
}
Please help me. I must handle it for my job.
Thank you.
Anne
[1317 byte] By [
anneff] at [2007-9-26 11:39:19]

Not really sure what the question is.
Are you creating a JVM in your C/C++ application?
Are you creating C/C++ threads in your C/C++ code?
If the answer to both of the above is no/false then you are not using C threads so there is no reason to use AttachCurrentThread and the problem has nothing to do with C and threads.
What is a "VC Console"? Do you mean you are running in in the Visual C++ environment but it doesn't work outside of it? Then the most likely reason is because there is something wrong with the environment (not the code) outside of VC.
The code samply you provide has no error checking. Does your real code have error checking? Every method call to the JNI stuff should check for errors. And every 'method' call in JNI code should check for exceptions.
Hi, thank you for your reply.
I am NOT creating a JVM in my C/C++ application.
The problem is when I call __declspec( thread ), the system crash.
Your suggestion is if I call from java to C++, for example, send data to C++, I do NOT need handle the thread whatever the C++ use thread and Socket.
You are right. The C++ code works well in VC++ environment. And the JNI code works well to call simple C++ code (testing).
I handle exception in Java side. That means I use try .. catch.. block to handle native method. But you mean I need check error and exception in C++ side ?
For example
jint err = env->MonitorEnter(obj);
if (err)
{
//todo
}
else
{
// todo
}
I will handle it in the real code.
I appreciate your suggestion.
Have a good day
anne