Java Interview Question
Use this advanced question and answer to prepare for your next Java interview.
Describe a potential way of creating a memory leak in Java. Give an example.
Because Java has automated memory management, it precludes code errors relating to allocation of memory for objects and reclaiming memory from objects. This prevents user errors arising due to incorrect code for memory management, but it does not avoid design flaws that can result in memory leaks.
Example of Design flaw:
We are required to implement a Cache. This requires storing objects that can be retrieved quickly. In order to implement a basic cache, we can use a HashMap.
Now, if the Cache program only implements the basic cache operations to insert, get, and delete objects from the Cache, it will result in a big memory leak. It is essential for a Cache to have a purging operation. This can occur over time, with usage or any other relevant factor.
If it is not included, then the Cache will keep growing while it is storing objects that will most likely not be used again. This is a memory leak which can be avoided by implementing a good cache eviction technique.