Java 如何定义析构函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29814050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:38:22  来源:igfitidea点击:

How to define destructors?

javaoopdestructor

提问by ema

    public class A {

    double wage;

    A(double wage){
    this.wage=wage;
    }

    }

//In this code I am supposed to define the constructors as well as destructors.

//在这段代码中,我应该定义构造函数和析构函数。

  • What is the code for defining a destructor?
  • 定义析构函数的代码是什么?

采纳答案by igreenfield

In Java, there are no destructorsbut you can use method Object#finalize()as a work around.

在 Java 中,有no destructors但您可以使用方法Object#finalize()作为解决方法。

The Java programming language does not guarantee which thread will invoke the finalize method for any given object. It is guaranteed, however, that the thread that invokes finalize will not be holding any user-visible synchronization locks when finalize is invoked. If an uncaught exception is thrown by the finalize method, the exception is ignored and finalization of that object terminates.

Java 编程语言不保证哪个线程将调用任何给定对象的 finalize 方法。但是,可以保证调用 finalize 的线程在调用 finalize 时不会持有任何用户可见的同步锁。如果 finalize 方法抛出未捕获的异常,则忽略该异常并终止该对象的终结。

class Book {
  @Override
  public void finalize() {
    System.out.println("Book instance is getting destroyed");
  }
}

class Demo {
  public static void main(String[] args) {
    new Book();//note, its not referred by variable
    System.gc();//gc, won't run for such tiny object so forced clean-up
  }
}

output:

输出:

Book instance is getting destroyed

System.gc()

Runs the garbage collector. Calling the gc 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 Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

The call System.gc() is effectively equivalent to the call:

Runtime.getRuntime().gc()

Object#finalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.

System.gc()

运行垃圾收集器。调用 gc 方法表明 Java 虚拟机花费精力来回收未使用的对象,以使它们当前占用的内存可用于快速重用。当控制从方法调用返回时,Java 虚拟机已尽最大努力从所有丢弃的对象中回收空间。

调用 System.gc() 实际上等效于调用:

运行时.getRuntime().gc()

对象#finalize()

当垃圾收集器确定不再有对对象的引用时,由垃圾收集器在对象上调用。子类覆盖 finalize 方法以处理系统资源或执行其他清理。

回答by igreenfield

Write your own method and use it. It is not recommended to override finalize method.

编写自己的方法并使用它。不建议覆盖 finalize 方法。