Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if I call a java function from multiple threads from C with JNI?

This link seems to suggest that "it just works": (pretty far on the bottom under 7.3 Attaching Native Threads) http://java.sun.com/docs/books/jni/html/invoke.html

I don't see how that is possible, is the embedded JVM going to start its own threads automatically? Or queue the JNI calls? How else could there be multiple calls to the same virtual machine. which I haven't instructed to do any threading?

Any way I can imagine that to work is, if the java code will simply be executed in the same calling thread as the c code. Is that correct? That would mean that I don't have to do any threading in Java.

like image 223
Blub Avatar asked Dec 28 '11 10:12

Blub


People also ask

Can two threads call the same function Java?

Only one thread can execute a method or block of code protected by the same object reference.

Can multiple threads read the same file Java?

Multiple threads can also read data from the same FITS file simultaneously, as long as the file was opened independently by each thread. This relies on the operating system to correctly deal with reading the same file by multiple processes.

Does JNI make the Java code machine dependent?

Native = platform dependent. JNI is optional and very specialized part of Java, you are not forced to use it for any of your Java coding. JNI is meant to be used for isolated tasks which absolutely cannot be done in JVM.

Can two threads access same method?

Two threads cannot access the same synchronized method on the same object instance. One will get the lock and the other will block until the first thread leaves the method. In your example, instance methods are synchronized on the object that contains them.


1 Answers

The jvm does not have to create its own threads, the method calls are executed on the native threads that make them. The AttachCurrentThread and DetachCurrentThread will take care of any necessary jvm internal state management, for example creating java Thread objects wrapping the native threads.

like image 52
josefx Avatar answered Oct 13 '22 00:10

josefx