Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k points)

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?

1 Answer

0 votes
by (46k points)

Using a WeakReference in Android isn't any different than using one in plain old Java. Here is a great guide which gives a detailed explanation: Understanding Weak References.

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.

 Here is an article laying out the problems: WeakHashMap is not a cache!

 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.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Oct 13, 2019 in Java by Ritik (3.5k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...