Tuesday, June 9, 2015

Memory Leak In Java

An advanced interview question is, "Can we have memory leaks in Java"? More often than not the interviewer wants to know how much you know Garbage Collector in Java.

What all objects are Garbage Collected and when. If we explain on the basis of this, the interviewer (who is just as human as you are) will be satisfied 9 times out of 10.

As to the answer to the question of Memory Leaks, it is a bit contentious issue with no concrete answer.

My take is a follows, Java as a language was designed to not let memory leaks of C creep in. Then daemon Garbage Collector, takes care of memory allocation and deallocation. Once the object is not referenced it will in time be Garbage collected and memory released. So on the face of it Java does not seem to have classic memory leaks of C.

To go deep into this, we first need to know what exactly is memory leak? Well memory leak occurs when some an application allocates (repeatedly) a piece of memory which is not acquired back after it is not longer referenced. Eventually program will throw OutOfMemory Exception.

Java Garbage Collector doe not let this happen. A case can be when memory is allocated faster than it is de-allocated. This is more of an programming issue.

How can we create memory leak in Java? By code bug so that either, memory fills faster than Garbage Collection or fooling Garbage Collection not to collect a piece of memory.

1. Static variable should not allowed to hold large data. They can cause memory leaks.
2. A cache (HashMap) with a badly written hascode() and equals(0 can lead to memory leaks. One can store the value to a Map but can't get it back.
3. Inner Classes referencing Outer class can lead to memory leak.
4. A long running Thread can cause memory leak in Java.
5. A simple code would be to keep on growing a Linked List in Java till OutOfMemory occurs.

1 comment:

  1. Hi Arpit,

    I love all the posts, I really enjoyed.
    I would like more information about this, because it is very nice., Thanks for sharing.
    I’m in my final year at college and at the moment I'm researching for my final year project. I’m looking to do it on data carving which is a technique used in digital forensics to extract known file information from unstructured raw data.
    So, let’s say I make a bit for bit image of a USB drive that has some deleted images on it, jpeg maybe.
    I can still recover this file by locating its header and footer information as its raw data is still on the drive after it has been deleted.
    Thanks a lot. This was a perfect step-by-step guide. Don’t think it could have been done better.

    Muchas Gracias,
    Bittu

    ReplyDelete