JNI Call in java thread
I made an example which works fine in the JAVA main
Thread, but crash in a new Thread, Why?
Is it possible to do something like that?
if no, how?
__
Main example:
same code but without thread
__
Thread example:
__
public class UserThread extends Threads{
private MyJNIObject myJNIObject;
public UserThread(){
try{
System.loadLibrary("myDLL.dll");
}catch(UnsatisfiedLinkError e){}
this.myJNIObject = new MyJNIObject();
}
public void run(){
this.myJNIObject.run();
[596 byte] By [
pimentoa] at [2007-10-2 23:23:55]

I guess that you load myDLL.dll to implement Java native methods. To realize the problem you should know the mechanizm of this process.
1. Java native methods are implemented by java.lang.ClassLoader while this class is being loaded,
2. At this moment System.loadLibrary("myDLL.dll"); should be called, because java.lang.ClassLoader looks for export functions in DLLs already loaded to implement Java native methods,
3. You call System.loadLibrary("myDLL.dll"); in non-static block but in some method when native methods should be already implemented.
4. java.lang.ClassLoader cannot find DLL with proper export functions and thows an exception (it happens before the method with System.loadLibrary("myDLL.dll"); is called).
My recomendations:
- call System.loadLibrary("myDLL.dll"); in a static block of the class with native method implemented (or in some place you sure that JVM will know where to get functions while loading a class with native methods),
- put the same block in other classes which native methods will be implemented, because you do not know the order in which these classes will be loaded.
The library is already load in a static way:
public class Library{
public static void initLib() {
try{
System.loadLibrary("myDLL.dll");
}catch (UnsatisfiedLinkerror e){}
}
}
This doesn't appear in my example, just to simplify.
I just want to know, how to do JNI call in an user thread?
PS: why dll is compiled with multithread DLL option.
Thanks.
If you call JNI from Java code in a JNI function you get JNIEnv* value to call JNI SDK and do nothing with the current thread. If you create in native (maybe C++) code a new thread then
- java references passed from a thread to a thread should be GLOBAL (create them from proper LOCAL references);
- before the first call of JNI SDK you call AttachCurrentThread;
- when in the thread JNI SDK will not be used call DetachCurrentThread;
- do not forget to delete GLOBAL references created at the end of your code.
> I made an example which works fine in the JAVA main
> Thread, but crash in a new Thread, Why?
>
Any number of possibilities. Some that I can think of.
1. You aren't testing return values and checking for java exceptions in your JNI code.
2. Something is wrong with your JNI (C) code.
3. Your C code doesn't work in multiple threads.
> Is it possible to do something like that?
Yes.