6

Are there any performance implications when calling machine code from Java's bytecode? Since machine code is "unmanaged", and it is not "aware" of Java's internals, maybe this causes JVM's internal schedulers to pause or something like that?

I am new to Java, so maybe this is not even relevant, please help.

I know that in Erlang they have this problem, where the VM basically stops while it is making calls to machine code. I hope this is not the case with Java. Is it?

akonsu
  • 28,824
  • 33
  • 119
  • 194
  • see http://stackoverflow.com/questions/1393937/disadvantages-of-using-java-native-interface as well – Ankit Tripathi Aug 29 '16 at 14:50
  • thanks for the comments. I never mentioned the problem of the JNI calls being slow. I was asking something different... – akonsu Aug 29 '16 at 14:51
  • What is your actual requirement?Does it includes calling native call necessarily? – Ankit Tripathi Aug 29 '16 at 14:53
  • I am writing an application that calls into a library that is written in C. I need to know if my calling C code would halt the VM like it does in Erlang. – akonsu Aug 29 '16 at 14:54
  • What do you mean with "halt"? Will it halt your current thread: of course, will it halt the rest of the JVM: (almost) definitely no. – Mark Rotteveel Aug 29 '16 at 15:08
  • Calling a native function will be having performance pitfalls in comparison of calling a java function.Poorly written JNI might crash or halt JVM also.There is nice article on best practices - https://www.ibm.com/developerworks/library/j-jni/ – Ankit Tripathi Aug 29 '16 at 15:09
  • ok.. in Erlang, the VM processes are not directly mapped to the system threads, it is the responsibility of the VM's scheduler to run them, not that of the OS, so when I make a native call in Erlang, the scheduler cannot run. I am asking if Java has a similar issue and whether my question is at all relevant here. – akonsu Aug 29 '16 at 15:10
  • @MarkRotteveel thanks. you said "(almost) definitely no" is it "almost no" or "almost definitely"? : ) – akonsu Aug 29 '16 at 15:13
  • I wish people read the question before voting to close it as a duplicate – akonsu Aug 29 '16 at 15:17
  • It is definitely no, most of the time. I'm sure you can find an edge case where a JNI call will be able to get the rest of the JVM grinding to a halt, but usually other threads of the JVM will make progress. – Mark Rotteveel Aug 29 '16 at 15:40

1 Answers1

12

Threads running native code will not halt JVM.

As soon as JNI method is called, Java thread switches to _thread_in_native state. Threads in this state are not counted during safepoint operations, i.e. when a stop-the-world event occurs (like garbage collection), JVM does not stop these threads. Conversely, threads in native state cannot stop JVM unless they perform a JNI upcall. When a native method returns, the thread switches back to _thread_in_Java state.

apangin
  • 92,924
  • 10
  • 193
  • 247