Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use WeakReference in Java and Android development?

I have been a java developer for 2 years.

But I have never wrote a WeakReference in my code. How to use WeakReference to make my application more efficient especially the Android application?

like image 495
Chris Avatar asked Sep 26 '22 19:09

Chris


People also ask

Why do we use Weakreference in 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. Suppose that the garbage collector determines at a certain point in time that an object is weakly reachable.

What's the difference between Softreference and Weakreference in Java?

A Soft reference is eligible for collection by garbage collector, but probably won't be collected until its memory is needed. i.e. garbage collects before OutOfMemoryError . A Weak reference is a reference that does not protect a referenced object from collection by GC.

What is strong reference in Android?

Strong reference: strong references are the ordinary references in Java. Anytime we create a new object, a strong reference is by default created. For example, when we do: MyObject object = new MyObject(); A new object MyObject is created, and a strong reference to it is stored in object.

Why do we use Weakreferences?

Weak Refernce Objects are needed to JVM platform to ensure means against the memory leaks.


1 Answers

Using a WeakReference in Android isn't any different than using one in plain old Java.

You should think about using one whenever you need a reference to an object, but you don't want that reference to protect the object from the garbage collector. A classic example is a cache that you want to be garbage collected when memory usage gets too high (often implemented with WeakHashMap).

Be sure to check out SoftReference and PhantomReference as well.

EDIT: Tom has raised some concerns over implementing a cache with WeakHashMap. Here is an article laying out the problems: WeakHashMap is not a cache!

Tom is right that there have been complaints about poor Netbeans performance due to WeakHashMap caching.

I still think it would be a good learning experience to implement a cache with WeakHashMap and then compare it against your own hand-rolled cache implemented with SoftReference. In the real world, you probably wouldn't use either of these solutions, since it makes more sense to use a 3rd party library like Apache JCS.

like image 235
dbyrne Avatar answered Sep 28 '22 08:09

dbyrne