Static singleton lifetime in Android

前端 未结 4 501
再見小時候
再見小時候 2020-12-02 14:25

I have some unclear situation:

Will static singletons be garbage collected after last reference holding Activity has been destroyed? Because there is no more referen

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-02 15:16

    You can not control when exactly Java objects become garbage collected. An object becomes eligible for garbage collection when there are no more (non-circular) references to it. With Android, further, you can not control when your Activity gets removed from memory.

    singletons are supposed to represent something which always exist.

    • You can't force any object to be garbage collected; you can request that the garbage collector runs with System.gc() but it's only a request.

    • If you want to make a "singleton" eligible for garbage collection, you'd probably want to have a method to set the static variable to null (and hope that nothing else had taken a copy of the reference). Obviously the next time anyone asked for an instance, it would need to be recreated. at which point it's not really a singleton, of course.

提交回复
热议问题