When is a leak not a leak?

At more than one interview I’ve been asked, “can you have a memory leak in Java?” Technically the answer is, no. Truthfully the answer is, sort of. Java can’t leak memory in the classic sense that languages like C and C++ can. In those languages (and others) it’s possible to allocate memory, drop it on the floor and lose it until the process exits. You can’t do that in Java. If you drop it on the floor, the garbage collector will find it. But you can put it somewhere and forget about it…like in a list or a map. It’s technically not a leak, because your application is still “using” it. But for all intents and purposes it walks, talks and acts like a leak.

There’s an article on IBM’s developerWorks site discussing leaks in Java. It actually uses a term I think is more accurate, “loitering.” The memory hasn’t been leaked, and it’s not doing anything…but it’s still hanging around. The solution, in Java, is to use references. More specifically, weak and soft references. They allow the garbage collector to collect objects, even if they’re still referenced…as long as those references are only weak or soft references.

Fun stuff, reminds me of why I miss Java sometimes.

Leave a Reply