这个问题是针对 android 或 java 的。 假设我有一个类的实例(甚至是一个线程)。
我希望为了防止忘记处置/关闭实例(并避免任何可能的内存泄漏),如果没有更多对该实例的引用,它将自动调用特定方法,处置/关闭自身(在线程的情况下,它可能会自行中断)。
有没有可能强制执行这样的事情? 如果需要,我不介意这种事情只发生在 GC 期间。
最佳答案
if there are no more references to this instance , it will automatically call a specific method , disposing/closing itself (in case of a thread , it will probably interrupt itself)
finalize()做你在这里描述的。但是你很少看到它被使用,而且在使用它的时候也有一些陷阱。由于您无法控制垃圾收集,因此您无法确定何时运行 finalize(如果有的话)!来自 api:
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.
您不能强制执行垃圾收集。您只能建议 JVM 使用 System.gc() 这样做, 但不能保证一定会完成。
关于java - android/java - 当没有对实例的引用时如何得到通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10704331/