Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)
The use of weak references is something that I've never seen an implementation of so I'm trying to figure out what the use case for them is and how the implementation would work. When have you needed to use a WeakHashMap or WeakReference and how was it used?

1 Answer

0 votes
by (46k points)

One problem with strong references is caching, particular with very large structures like images. Suppose you have an application which has to work with user-supplied images, like the web site design tool I work on. Naturally you want to cache these images, because loading them from disk is very expensive and you want to avoid the possibility of having two copies of the (potentially gigantic) image in memory at once.

Because an image cache is supposed to prevent us from reloading images when we don't absolutely need to, you will quickly realize that the cache should always contain a reference to any image which is already in memory. With ordinary strong references, though, that reference itself will force the image to remain in memory, which requires you to somehow determine when the image is no longer needed in memory and remove it from the cache, so that it becomes eligible for garbage collection. You are forced to duplicate the behavior of the garbage collector and manually determine whether or not an object should be in memory.

Understanding Weak References

Related questions

0 votes
1 answer
asked Jul 13, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...