一个在单例对象内部的包装变量能否在单例不为null的情况下被垃圾回收?

huangapple 未分类评论46阅读模式
英文:

Can a wrapper variable within a Singleton object get garbage collected while Singleton is not null?

问题

在这个 Singleton 实例中,当单例实例仍不为 null 时,这个 private Long severDate 是否会被垃圾回收?

我在一个 Android 应用中遇到了这个问题。想知道 Android 操作系统是否会以某种方式释放未使用的单个内存值。

public class DataHolder {

    private static DataHolder self;

    private Long severDate; 
    private int numb;

    public static synchronized DataHolder getInstance() {
        if (self == null) {
            self = new DataHolder();
        }
        return self;
    }

}
英文:

In this Singleton instance, can this private Long severDate become garbage collected when the singleton instance is still not null?

I encountered this is in an Android app. Wondering Android OS somehow freeing unused individual memory values.

public class DataHolder {

    private static DataHolder self;

    private Long severDate; 
    private int numb;

    public static synchronized DataHolder getInstance() {
            if (self == null) {
                self = new DataHolder();
            }
            return self;
    }
 
}

答案1

得分: 0

直到"Long severDate"有一个引用指向它,垃圾回收不会删除它。现在一切都取决于使用情况,您是否在某些类中创建了此单例类的实例。
附言:在安卓中,请确保在onCreate方法中创建该类的对象。

英文:

Until "Long severDate" has a references to it, GC wont be deleting it. Now it all depends on the useCase whether u have created the instance of this singleton class in some classes or not.
P.S: In android make sure that u create the obj of this class in onCreate method.

huangapple
  • 本文由 发表于 2020年7月26日 16:38:37
  • 转载请务必保留本文链接:https://java.coder-hub.com/63097947.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定