java - android/java - 当没有对实例的引用时如何得到通知

标签 java android memory-leaks interrupted-exception

这个问题是针对 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/

相关文章:

android - 4. 0 (API 14) SDK 平台是 "Obsolete"!我还应该设法下载和使用它吗?

android - Kotlin 从嵌套的 forEach 返回@forEach

python - 在 Python 中卸载模块

c++ - 使用字符串映射 vector C++ 时可能存在内存泄漏

java - 将字符串从 UTF-8 转换为 ANSI 并将其显示为 UTF-8

java - 如何修复 Netbeans 7.2.1 无法正确构建/编译?

java - 在Java中生成文本文件时应该使用 "\r\n"还是 "\n"?

java - 使用存储库在本地数据库/位置和网络之间同步

java - 运行内存密集型 Java 应用程序后操作系统变慢的原因是什么?

java - 我可以更改持久性单元@GenerateValue 中 GenerationType 的默认(自动)值吗?