>>Is it possible in java too or do you need to hardcode the function name
>>inside jni?
> You either have to hard-code the function name in the JNI code, or tell the JNI
> code somehow what the name of the function is. Overall the former is simpler
[quoted text clipped - 39 lines]
> of it everywhere. JNI only needs to know about (and hard-code) the one
> Callback method.
Nice and simple abstract callback layer. However, I have always wondered
whether its safe to call java method from _any_ native thread. Virtual
machine does not bother the origin thread it is just us to maintain a
thread safety code when doing callbacks from native side?
Chris Uppal - 27 Jul 2005 11:17 GMT
> However, I have always wondered
> whether its safe to call java method from _any_ native thread. Virtual
> machine does not bother the origin thread it is just us to maintain a
> thread safety code when doing callbacks from native side?
I'm not sure that I have understood your question properly. If the following
doesn't answer your question then please ask again.
There are two parts to this.
The first part is that there are definite rules about which threads are allowed
to call back from native code into Java. If thread is executing native code
because that code has been called from Java, then it's OK for it to call back
into Java (on the same thread). If a thread is the one that originally created
the JVM, then it can call into Java whenever it wants. Otherwise, as I
understand it (I've never had to use this so I may be wrong), a thread can only
call Java code if it has registered itself with the JVM by using the JNI
AttachCurrentThread() function (or similar). Basically you can only call Java
code from native threads that the JVM "knows" about. A related problem for JNI
programmers, is that the references to Java objects that Java provides when it
invokes JNI code, are only valid on that thread. If the programmer wants to
store a reference to the object for use on another thread, then s/he has to
convert the reference to a so-called "global" reference (and remember to
release it later). So, for instance, the Callback object in my example
couldn't just be stored or passed from thread to thread in the OP's JNI code --
if he wanted to do that, then he'd have to code for it specially, following the
JNI rules.
The second part is that -- providing the above rules are followed -- the
callback can be invoked from any thread. In this case the picture is just the
same as if the callback had been invoked from Java code running in a different
(or potentially different) Java Thread. If that possibility is allowed by your
application design (it may not be), then you have to code for it by using
synchronized methods and blocks in the usual way. (It is also possible to
acquire/release the locks associated with any object directly from JNI, but I'd
think that would usually be a very bad idea -- and a lot of extra effort too.)
-- chris