今天继续在看Think in java .看到讲初始化这章,讲到System.gc();进行垃圾回收,强制进行终结动作(finilize()),一时兴起看了下System.gc()方法的源代码.如下
public static void gc() {
Runtime.getRuntime().gc();
}
继续去看Runtime类的gc()方法
public native void gc();
看了下上面方法的JAVADOC
/**
* Runs the garbage collector.
* Calling this method suggests that the Java virtual machine expend
* effort toward recycling unused objects in order to make the memory
* they currently occupy available for quick reuse. When control
* returns from the method call, the virtual machine has made
* its best effort to recycle all discarded objects.
*
* The name gc
stands for "garbage
* collector". The virtual machine performs this recycling
* process automatically as needed, in a separate thread, even if the
* gc
method is not invoked explicitly.
*
* The method {@link System#gc()} is the conventional and convenient
* means of invoking this method.
*/
native关键字 说明垃圾回收调用的是本地方法,JAVADOC说明垃圾回收是回收当占用内存空间的无用对象,垃圾回收只在需要的时候进行回收。和你调不调用垃圾回收没有啥关系,即使你不调用需要的时候JVM也会自动调用垃圾回收的方法
下面说下native关键字
Native方法一般用于两种情况:
1)在方法中调用一些不是由java语言写的代码。
2)在方法中用java语言直接操纵计算机硬件
如果使用了native方法也就丢失了java的方便性和安全性。Native方法的执行依赖于JVM的设计者,
在sun的JVM中,可以通过JNI(Java Native Interface) API接口来实现本地化。