使用 finalize() 清理活动;

Cleanup activities with finalize() ;

我读到了 finalize() 方法,这是垃圾收集器在释放内存之前调用的方法。 从文档中,finalize 用于进行清理活动。但是 "things" 在这个 "cleanup activities"

中清理了什么

摘自 Bruce Eckel 的“Java 中的思考”一书:

It would seem that finalize( ) is in place because of the possibility that you’ll do something Clike by allocating memory using a mechanism other than the normal one in Java. This can happen primarily through native methods, which are a way to call non-Java code from Java. C and C++ are the only languages currently supported by native methods, but since they can call subprograms in other languages, you can effectively call anything. Inside the non-Java code, C’s malloc( ) family of functions might be called to allocate storage, and unless you call free( ), that storage will not be released, causing a memory leak. Of course, free( ) is a C and C++ function, so you’d need to call it in a native method inside your finalize( ).

After reading this, you probably get the idea that you won’t use finalize( ) much.

典型的清理类型是释放实例分配的任何系统资源,例如 FileInputStream.

情况下的文件描述符

请注意,好的 Java 程序永远不会依赖对象终结器中执行的清理,而是会明确要求对象在其使用到期时释放资源。

不幸的是,JDK 中有一些难看的示例,其中终结器是唯一提供的机制。一个臭名昭著的是 DirectByteBuffer,它分配本机(堆外)内存并且不提供 public 方法来释放它。