Java Singleton object 能否仅部分被垃圾回收?

Can a Java Singleton object be garbage collected only in part?

据我所知,Java 单例 object 不能被垃圾回收,除非加载此 class 的上下文(class 加载器)是本身符合垃圾 collection.

问题 #1: 是这样还是有其他情况它可能被垃圾收集了?

在我的应用程序中,我有一个 Android Activity 创建单例 object。当我的应用程序在后台运行时设备内存不足时,如果我尝试打开它并将其带回前台,我会看到单例 object 已被销毁并重新初始化。

问题 #2: 如果必须释放内存并且对单例 object 进行垃圾回收,是否存在单例 object 可能无法完全进行垃圾回收而仅对其某些静态变量进行垃圾回收的情况?

In my app I have an Android Activity creating a singleton object. When the device runs out of memory while my app is on the background, if I try to open it and bring it back to the foreground I see that the singleton object has been destroyed and it's reinitialized.

是的。这与 'garbage collection' 有关。那是 android 卸载整个应用程序,这是非常不同的。

If memory must be freed and a singleton object is garbage collected, is there any case where the singleton object might not get garbage collected totally and instead only some of its static variables will be garbage collected?

因此,这个问题多半是不合逻辑的。

有两种完全不同的机制在起作用:

  1. 有一些空闲 CPU 周期 and/or 一些内存压力,所以做一些垃圾收集。您不会注意到这些 - 如果您可以在源代码中看到它,它就不会被垃圾收集。

  2. 这还不够好/正在设备上启动一个不同的进程和垃圾收集 运行 进程没有滚雪球的机会来释放足够的空间。在这种情况下,您的 entire android 应用会直接卸载。你被狠狠地杀死了,下次你的应用程序受到关注时(用户运行它,或者你有一些触发的钩子),你的应用程序将从头开始重新加载。

因此没有半卸载。无论垃圾收集器做什么,根据定义都是不可观察的(如果它已经被收集,它就不会被收集),如果您的应用程序被卸载,整个事情就会消失。