Home > Java > Java Tutorial > body text

Java关键字之finalize使用的示例代码

黄舟
Release: 2017-03-15 13:24:27
Original
1600 people have browsed it

Java中提供了finalize方法,在垃圾回收器在进行内存释放时会首先调用finalize,但会有一些误区。

1)、对象可能不被垃圾回收。

2)、垃圾回收并不等于"析构",finalize不是析构函数

3)、垃圾回收只与内存有关。

4)、垃圾回收和finalize都是靠不住的,只要JVM还没有到内存耗尽的地步,它是不会浪费时间进行内存回收的。

finalize的调用前提情况:

1)、所有对象被Garbage Collection自动调用,比如运行System.gc()的时候

2)、程序退出时为每个对象调用finalize()方法

3)、显式的调用finalize方法

并不建议使用finalize方法完成非内存资源的清理工作,但建议用于:(1)清理本地对象(通过JNI创建的对象)。(2)作为确保

某些非内存资源的释放(socket,文件,端口等等)

finalize()方法的通用格式:

protected void finalize()
{
    //finalization code here
}
Copy after login

简单示例代码:

public class FinalizationDemo {
    public static void main(String[] args) {
        Cake c1 = new Cake(1);
        Cake c2 = new Cake(2);
        Cake c3 = new Cake(3);
        c2 = c3 = null;
        System.gc(); //Invoke the Java garbage collector  
    }
}
class Cake extends Object {
    private int id;
    public Cake(int id) {
        this.id = id;
        System.out.println("Cake Object " + id + "is created");
    }
    protected void finalize() throws java.lang.Throwable {
        super.finalize();
        System.out.println("Cake Object " + id + "is disposed");
    }
}
Copy after login

运行结果:

Cake Object 1is created
Cake Object 2is created
Cake Object 3is created
Cake Object 3is disposed
Cake Object 2is disposed
Copy after login


The above is the detailed content of Java关键字之finalize使用的示例代码. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!