以下是JDK中的描述:
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.
当垃圾回收器发现一个对象没有任何引用的时候,就会调用这个对象的类对应的finalize方法。子类重写finalize方法,一般是为了处理系统资源或者做一些其他的清理工作。
The general contract of
finalize
is that it is invoked if and when the Java? virtual machine has determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, except as a result of an action taken by the finalization
of some other object or class which is ready to be finalized. The finalize
method may take any action, including making this object available again to other threads; the usual purpose of
finalize
, however, is to perform cleanup actions before the object is irrevocably discarded. For example, the finalize method for an object that represents an input/output connection might perform explicit I/O transactions to break the connection
before the object is permanently discarded.
一般来说,finalze方法都是在Java虚拟机发现去除那些已经被执行了finalize的对象之外,没有任何活动的线程能够引用到该对象的时候调用。在finalze方法里,可以做任何事情,甚至让该对象重新可被其他线程引用;但是一般来说,finalize方法的通常目的是在该对象真正被回收之前做一些清理的工作。比如,一个代表输入/输出连接的对象,它的finalize方法可能会在自己被回收之前中断对应的I/O连接。
The finalize
method of class
Object
performs no special action; it simply returns normally. Subclasses of
Object
may override this definition.
Object类的finalize方法没做任何事,只是简单的返回。而Object的子类可以重写这个方法。
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方法中抛出了一个没有被catch的异常,这个异常会被忽略,finalize方法会中止。
After the
finalize
method has been invoked for an object, no further action is taken until the Java virtual machine has again determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, including
possible actions by other objects or classes which are ready to be finalized, at which point the object may be discarded.
一个对象的finalize方法被调用之后,这个对象就不可以被任何活动的线程再次引用了,这个对象也不能再进行任何的操作,包括被那些已经执行finalize方法的对象或者类,直到被Java虚拟机回收。
The
finalize
method is never invoked more than once by a Java virtual machine for any given object.
一个特定的对象的finalize方法绝对不会被Java虚拟机调用超过一次。
Any exception thrown by the
finalize
method causes the finalization of this object to be halted, but is otherwise ignored.
finalize方法抛出的任何异常,会导致finalize方法的中止,但是这也会被忽略。(意思应该说是,虽然抛出了异常,finalize中止,没法继续执行,但是再此之后,对象还是会不可以被操作,直到它被Java虚拟机回收掉。)
原文地址:http://blog.csdn.net/cyp331203/article/details/44461021