I've come across this android code below. Is there ever a use case of creating a static weakreference object in a service to get its reference? I know that static variables are not eligible for Garbage collection. In general, Does creating a weak reference of any static variable change its gc properties?
for example:
private static WeakReference<MyService> mService;
public static MyService getInstance(){
if(mService != null){
return mService.get();
}
return null;
}
And in my onCreate
public void onCreate(){
super.onCreate();
mService = new WeakReference<MyService>(this);
}
A WeakReference is good when you want to let an object head for garbage-collection without having to gracefully remove itself from other objects holding an reference. In scenarios such as publish-subscribe or an event bus, a collection of references to subscribing objects is held.
Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed. Weak references are most often used to implement canonicalizing mappings.
Use long weak references only when necessary as the state of the object is unpredictable after finalization. Avoid using weak references to small objects because the pointer itself may be as large or larger. Avoid using weak references as an automatic solution to memory management problems.
As stated by Java documentation, weak references are most often used to implement canonicalizing mappings. A mapping is called canonicalized if it holds only one instance of a particular value. Rather than creating a new object, it looks up the existing one in the mapping and uses it.
The WeakReference is so the service can be garbage collected even if the activity still has a variable referring to it. The static means it will persist after the activity ends. So you get a reference to the Service that persists between calls but still allow the Service to be gced. (The WeakReference itself can't be GCed, but shouldn't take much in the way of memory).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With