Java Memory Puzzle
Instead of telling you some mystery of Java memory, it is time for you to put on your thinking caps. I had a discussion a few weeks ago with one of my subscribers of whether you should null your local variables, to make things easier for the garbage collector. His understanding was that the local variables will be stored on the stack and thus popped off at the end of the method call anyway, so nulling them was a waste of time. In almost all situations, he is right. However, he had a class that did something most peculiar, something like this:
When you run this you will always get an OutOfMemoryError, even though the local variable data is no longer visible outside of the code block.
So here comes the puzzle, that I'd like you to ponder about a bit. If you very politely ask the VM to release memory, then you don't get an OutOfMemoryError:
Copyright Heinz Kabutz 2009
Aristotelous 84, Korakies, Akrotiri, Chania, Crete, 73100, Greece
Why does this work?