2006-05-13

Java: Memory leaks

For all C++ monstrosity it brainwashes yet.

About six months ago guys had a problem with j2me app. Run tests: 1st passed, 2nd raises OutOfMemory error. Change the tests running order — now the ex-first test raises OutOfMemory. I looked at this, but could not tell anything reasonable.

I've just remembered about it and it seems to me I've understood what the kind of trouble was that. The problem is exactly between the two lines:

class MemoryLeak {
static int[] buffer = new int[0];

public static void reinitialise(int maxsize) {
if(buffer.length < maxsize)
buffer = new int[maxsize];
}
}


The problem is that Java machine acts too straightforward. The first call of reinitialise is normally, during the second call at first it tries to allocate memory for a new massive and in the case of success the result is assigned to a variable. And only after that the memory to which buffer was referred will be available to Garbage Collector. As a result for a normal work it is required 2*maxsize of memory. The solution is to set buffer to null before the memory allocation.

But IMHO Java machine could take care of it. And in rare cases when double memory allocation is required it is better to be described explicitly.

public static void reinitialise(int maxsize) {
if(buffer.length < maxsize) {
int tmpbuf[] = new int[maxsize];
buffer = tmpbuf;
}

No comments:

Post a Comment