Java native
method provides a mechanism for Java code to call OS native code, either due to functional or performance reasons.
Example:
606 public native int availableProcessors();
617 public native long freeMemory();
630 public native long totalMemory();
641 public native long maxMemory();
664 public native void gc();
In the corresponding Runtime.class
file in OpenJDK, located in JAVA_HOME/jmods/java.base.jmod/classes/java/lang/Runtime.class
, contains these methods and tagged them with ACC_NATIVE
(0x0100
), and these methods do not contain the Code attribute, which means these method do not have any actual coding logic in the Runtime.class
file:
availableProcessors
: tagged as native and no Code attributefreeMemory
: tagged as native and no Code attributetotalMemory
: tagged as native and no Code attribute maxMemory
: tagged as native and no Code attribute gc
: tagged as native and no Code attributeThe in fact coding logic is in the corresponding Runtime.c file:
42 #include "java_lang_Runtime.h"
43
44 JNIEXPORT jlong JNICALL
45 Java_java_lang_Runtime_freeMemory(JNIEnv *env, jobject this)
46 {
47 return JVM_FreeMemory();
48 }
49
50 JNIEXPORT jlong JNICALL
51 Java_java_lang_Runtime_totalMemory(JNIEnv *env, jobject this)
52 {
53 return JVM_TotalMemory();
54 }
55
56 JNIEXPORT jlong JNICALL
57 Java_java_lang_Runtime_maxMemory(JNIEnv *env, jobject this)
58 {
59 return JVM_MaxMemory();
60 }
61
62 JNIEXPORT void JNICALL
63 Java_java_lang_Runtime_gc(JNIEnv *env, jobject this)
64 {
65 JVM_GC();
66 }
67
68 JNIEXPORT jint JNICALL
69 Java_java_lang_Runtime_availableProcessors(JNIEnv *env, jobject this)
70 {
71 return JVM_ActiveProcessorCount();
72 }
And these C
coding is compiled into the libjava.so
(Linux) or libjava.dll
(Windows) file, located at JAVA_HOME/jmods/java.base.jmod/lib/libjava.so
:
Reference