Explain Codes LogoExplain Codes Logo

How to use WeakReference in Java and Android development?

java
weak-references
memory-management
garbage-collection
Alex KataevbyAlex Kataev·Feb 22, 2025
TLDR

WeakReference in Java or Android is handy for memory management as it allows objects to be willingly eaten by garbage collector (🗑️) when there are no strong references. This is especially useful in memory-sensitive platforms like Android. Think of them as an offering to the mighty garbage collector.

MyObject obj = new MyObject(); // Create your object WeakReference<MyObject> weakRef = new WeakReference<>(obj); // Make a WeakReference offering obj = null; // The strong link is gone. Only the WeakReference remains // Check if the object is still around or the garbage collector had a snack MyObject retrievedObj = weakRef.get(); if (retrievedObj != null) { // Your object lives on 🥳🎉 } else { // The garbage collector was hungry 😢 }

Key Points:

  • new WeakReference<>(obj): You've created a weak reference.
  • weakRef.get(): You're checking if your offering was accepted.

Implementing weak references for caching

Caching with weak references ensures your cached objects are not hoarded unnecessarily. They offer themselves up for the memory purge when pressure mounts. They're the heroic volunteers of memory management.

WeakHashMap<MyKey, Bitmap> imageCache = new WeakHashMap<>(); // ... // Offer a bitmap to the cache, to be kept or collected as needed imageCache.put(myKey, myBitmap);

The WeakHashMap automatically removes entries when the key is no longer in ordinary use.

Observing through weak references

In observer patterns, weak references for listeners can help avoiding retention of objects past their expiration date. They act like a fading echo, dimming until they can't be heard—unless you make an effort to listen in.

WeakReference<MyListener> weakListenerRef = new WeakReference<>(myListener); myObservables.addListener(weakListenerRef);

Listener objects will be garbage collected once they're no longer in strong use elsewhere in your code, removing themselves from the list and freeing up memory.

Using weak references in Android views

In Android, WeakReference can hold temporary references to views, keeping them from holding up an Activity's garbage collection after it's been closed.

WeakReference<View> weakViewRef = new WeakReference<>(myView); // ... View view = weakViewRef.get(); if(view != null) { // Display a hello toast }else{ // View was cleared up, nothing to see here folks! }

Pitfalls

Just like a party where you rely on your guests cleaning up, things can get a bit messy. GC can happen unpredictably, meaning weak references may seem to disappear randomly. When using WeakReferences, always prepare for the inevitable null.

Reference your references

Java offers other types of referential objects: SoftReference and PhantomReference.

  • SoftReferences are like shrines to the Garbage Collector that he'll remove last.
  • PhantomReferences are used to schedule post-garbage-collection clean-up actions; it's like your post-party cleaning crew.