Java - finalize()

In particular, there is a method of the system class called GC. The GC method suggests that the Java Virtual Machine runs the garbage collection process. So it's going to tell the Virtual Machine to run the garbage collection, but there's no guarantee that the Virtual Machine will do.

Of course, the garbage collector might well have run half-way through all of these objects being created as well. So calling GC is a suggestion that it should run, but it's not a guarantee.

While garbage collection takes place, your application is temporarily suspended, and it won't resume until garbage collection is complete. For this reason, we want garbage collections to be quick and reasonably infrequent And in fact, if your application's finished, the GVM will be destroyed and removed from memory and the garbage collector will never run, these Finalize methods will never be called. So you cannot rely on the Finalize method being called.

So we're not using Finalize to correct the problem, but at least send out a warning that something could be wrong. Maybe that's pretty much the only real use for the Finalize method.

public static void main(String[] args) {
    Runtime runtime = Runtime.getRuntime();

    long availableBytes = runtime.freeMemory();
    System.out.println("Available Memory:" + availableBytes / 1024 + "k");

    for (int i = 0; i < 1000; i++) {
        User user = new User("Bill" + i);
    }

    availableBytes = runtime.freeMemory();
    System.out.println("Available Memory:" + availableBytes / 1024 + "k");

    System.gc();

    availableBytes = runtime.freeMemory();
    System.out.println("Available Memory:" + availableBytes / 1024 + "k");
}
public class User {
    String name;

    public User(String name) {
        this.name = name;
    }

    public void finalize() {
        System.out.println("this object is being gc'd. ");
    }
}

控制台打印结果:

Available Memory:244736k
Available Memory:244736k
Available Memory:18984k
this object is being gc'd. 
this object is being gc'd. 
this object is being gc'd. 
...
this object is being gc'd. 

this object is being gc'd.  一共打印38次,每次运行时打印的次数都不一样。

说明finalize的执行结果是不可靠的。

猜你喜欢

转载自blog.csdn.net/A_bad_horse/article/details/114259960