Static singleton lifetime in Android

前端 未结 4 505
再見小時候
再見小時候 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:20

    No, because if it's a singleton, it's stored as a static field in its class, and usually singletons are not destroyed by clients, ie you wouldn't put a static method deleteInstance() which sets the reference to null so that if nobody else uses it, it's eligible for garbage collection. For static fields, garbage collection will happen when the classloader which loaded the class is discarded.

    For this reason, the keyword static itself may cause memory leaks, if it references Activity objects, so you should be very careful when using it.

提交回复
热议问题