Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue about weakreferences

I have one or two weakreferences in my program.

Just for example:

ClassX myClassX= new ClassX(); //Line 1
WeakReference<ClassX> myWeakClassX = new WeakReference<ClassX>(myClassX); //Line 2
if(myWeakClassX.get() != null) // Line 3
{
    //do something with reference //Line 4
}

My question:

How is it ensured that when at line 3 myWeakClassX.get() has a valid reference to an Object, it is also valid at line 4? I can imagine that if you are really unlucky, the GC does his job exactly "between" line 3 and 4. Please bear with me, because i'm relatively new to Android/Java..

Thanks for any explanation.

like image 217
MMike Avatar asked Feb 21 '26 00:02

MMike


1 Answers

In Java, first thing to understand is Garbage Collector reclaims memory from objects which are eligible for garbage collection

Question is how is the eligibility defined ?

eligibility is decided based upon which kind of references are pointing to that object.

Why we need Weak Reference ?

If you create a Strong reference to an object, the object cannot be garbage collected. Whereas, A weak reference, simply put, is a reference that isn't strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector's ability to determine reachability for you, so you don't have to do it yourself.

Issue here

Weak reference isn't strong enough to prevent garbage collection, so you may find (if there are no strong references to the class) that myWeakClassX.get() suddenly starts returning null.

What is the other option ?

Soft Reference

You use a SoftReference when you want the referenced object to stay alive until the host process is running low on memory. The object will not be eligible for collection until the collector needs to free memory. Loosely stated, binding a SoftReference means, "Pin the object until you can't anymore."

This way myWeakClassX.get() will not be null.

Examples of where we can use ?

  1. In any secondary threads where you create a reference to the activity.

    WeakReference weakActivity;

    //In AsyncTask onPostExecute Method Activity activity = weakActivity.get(); if (activity != null) { // do your stuff with activity here }

  2. If you can referring to an Activity context elsewhere, you can use Weak reference.

  3. While handling bitmap resources in imageview in another thread http://developer.android.com/training/displaying-bitmaps/process-bitmap.html

  4. If you are creating any Hashmap or any widget to hold any data, you can use Weak reference. http://developer.android.com/reference/java/util/WeakHashMap.html

  5. Usage is unlimited. It is up to the developer to utilize it at right places.

like image 151
Prem Avatar answered Feb 23 '26 02:02

Prem