本文介绍了调用本机方法时JVM必须做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 在调用声明为 native 的Java方法时,JVM运行时必须执行的常规步骤是什么?What are the usual steps that the JVM runtime has to perform when calling a Java method that is declared as native? HotSpot 1.8.0 JVM如何实现JNI函数调用?涉及哪些检查步骤(例如,返回后未处理的异常?),JVM要执行哪些簿记(例如本地参考注册表?),以及在调用本机Java方法之后控制在哪里?如果有人可以提供原生HotSpot 1.8.0代码的入口点或重要方法,我也将不胜感激。How does a HotSpot 1.8.0 JVM implement a JNI function call? What checking steps are involved (e.g. unhandled exceptions after return?), what bookkeeping has the JVM to perform (e.g. a local reference registry?), and where does the control go after the call of the native Java method? I would also appreciate it if someone could provide the entry point or important methods from the native HotSpot 1.8.0 code.免责声明:我知道我可以自己阅读代码但事先的解释有助于快速找到我的代码。此外,我发现这个问题值得谷歌搜索。 ;)Disclaimer: I know that I can read the code myself but a prior explanation helps in quickly finding my way through the code. Additionally, I found this question worthwhile to be Google searchable. ;)推荐答案与简单的C函数调用相比,从Java调用JNI方法相当昂贵。 HotSpot通常执行以下大多数步骤来调用JNI方法:Calling a JNI method from Java is rather expensive comparing to a simple C function call.HotSpot typically performs most of the following steps to invoke a JNI method: 创建堆栈框架。 根据ABI将参数移动到正确的寄存器或堆栈位置。 将对象引用换行到JNI句柄。 获取 JNIEnv * 和 jclass 用于静态方法并将它们作为附加参数传递。 检查if应该调用 method_entry 跟踪函数。 如果方法 synchronized 。 检查本机功能是否已链接。函数查找和链接是懒惰地执行的。 将线程从 in_java 切换到 in_native 州。 调用原生函数 检查是否需要安全点。 将线程返回 in_java 州。 如果锁定则解锁显示器。 通知 method_exit 。 解包对象结果并重置JNI处理块。 处理JNI异常。 删除堆栈框架。Create a stack frame.Move arguments to proper register or stack locations according to ABI.Wrap object references to JNI handles.Obtain JNIEnv* and jclass for static methods and pass them as additional arguments.Check if should call method_entry trace function.Lock an object monitor if the method is synchronized.Check if the native function is linked already. Function lookup and linking is performed lazily.Switch thread from in_java to in_native state.Call the native functionCheck if safepoint is needed.Return thread to in_java state.Unlock monitor if locked.Notify method_exit.Unwrap object result and reset JNI handles block.Handle JNI exceptions.Remove the stack frame.此过程的源代码可在 SharedRuntime :: generate_native_wrapper 。如您所见,开销可能很大。但在许多情况下,上述大部分步骤都不是必需的。例如,如果本机方法只对字节数组执行某些编码/解码,并且不抛出任何异常,也不会调用其他JNI函数。对于这些情况,HotSpot有一个非标准(并且未知)约定,名为 Critical Natives ,讨论过这里。As you can see, an overhead may be significant. But in many cases most of the above steps are not necessary. For example, if a native method just performs some encoding/decoding on a byte array and does not throw any exceptions nor it calls other JNI functions. For these cases HotSpot has a non-standard (and not known) convention called Critical Natives, discussed here. 这篇关于调用本机方法时JVM必须做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-17 20:24
查看更多