javajvmjvm-hotspot

How does java virtual machine connect user level function to its internal functions?


How does JVM translate API to its implementation inside JVM?

Is it similar to "Linux Kernel syscall" implementation? If so, where are these interfaces? Hope to see the source code.

enter image description here

Figure from https://www.artima.com/insidejvm/ed2/introarch4.html

e.g. ,

Any Java virtual machine implementation must take care to connect these methods of class ClassLoader to the internal class loader subsystem.

https://www.artima.com/insidejvm/ed2/jvmP.html


Solution

  • The API you have linked (https://docs.oracle.com/javase/7/docs/api/), is basically an ordinary class library. When you have installed a JDK, there will be file, src.zip or src.jar, depending on the version, containing the plain Java source code of most of this library. In all versions up to and including Java 8, the compiled API classes are delivered as ordinary jar files, the majority of the API classes being in rt.jar. Starting with Java 9, new module files are used, still, the majority of the API is implemented as ordinary Java code.

    You can even browse the source code of certain versions online, e.g. this is the implementation of Object.toString() of version 8, update 40, beta 25, hosted at grepcode.com.

    So for most methods, there is nothing “similar to ‘Linux Kernel syscall’” involved when you invoke an API method. It works like an ordinary method invocation and the optimizer may even inline the JRE specific code into your application’s code at runtime. You may also step into the JRE’s code while debugging.

    Only a few methods are not implemented as plain Java code, e.g. Object.getClass() is a native method that can only be implemented in a JVM specific way.

    There are two general ways to implement these methods. There is a standardized interface, JNI, allowing the interaction of arbitrary native code and Java code. It includes a special linkage between invocations of Java methods declared native and their implementation via JNI. But some methods are handled as intrinsic operations by the JVM instead, which implies that the invocations of these well-known methods (e.g. getClass()) is handled directly by the interpreter/optimizer like a dedicated bytecode instruction. This very efficient handling is sometimes even used for methods, which have an ordinary Java implementation, when there is a platform specific, more efficient alternative. E.g, Integer.rotateLeft and rotateRight have a pure Java implementation, but if the actual CPU used at runtime has dedicated instructions for bitwise rotation, all optimizing JVMs will replace the invocations of these method with intrinsic operations using these CPU instructions.