Sunday, August 31, 2008

Java memory leak

One of fun things in java is that you don't need to release the memory of your application, this future effect dramatically on the way you write code.
For example: if you allocate some objects in java in a method and suddenly an exception is thrown you don't need to free the memory, the GC will do it for you.
In C++ for example is very disturbing problem. Since you have to release the memory you allocated in case of failure.
Student a;
Try {
Int I = getIdForStudent();
a = new Student(id);
int ave = a.getAverage()
}
catch (...){
// should we release memory of a?
}
Here you can see the problem of this issue, even the allocation can be fail. Then we don't even know if we should release the memory or not. Luckily in java we don't have that issue.
However, it doesn't mean we don't need to release the memory in java!
In order to understand how you are release memory in java you have to understand how the garbage collector works. The GC scan the memory of the application looking for objects that doesn't have reference to other objects or has reference to objects that are not connected to other objects, the garbage collector release the memory of such objects once it found them.
Therefore, if you have a list of students and the user removes one of the students, the user should be removed from the list as well.It's not always that simple, I worked on one projects that we have a log event and the log event developer decided to hold a reference to the objects that related to the log record. For example:
Student Moshe was created: contains the object Moshe.
After some working we sense that we have a serious memory problem. I examine the code closely and I saw that the object LogEventRecord holds a reference to the Student object; it means that the student object that in our case holds a lot of references as well was never deleted from the memory! Therefore, we tie the student object with weak reference so the garbage collector will collect the object despite its connection to the event log. The application can fetch the data from the database via the DAL layer, if you open the event log and ask for more details on the student. The upside is that we release the memory and the downside is that fetching the log event includes execute queries from the database.