Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why have a static weakreference to service object?

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);
}
like image 733
Daniel P Avatar asked Feb 04 '15 01:02

Daniel P


People also ask

Why WeakReference?

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.

When to use WeakReference android?

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.

When to use WeakReference c#?

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.

What is the purpose of a weak reference?

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.


1 Answers

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).

like image 130
Gabe Sechan Avatar answered Oct 06 '22 12:10

Gabe Sechan