I came across this today and I thought I'd share it as I found it interesting. I ran Garbage.java on two different platforms (see end of post for code).
OS X: OS X 10.5.8 x86 +
Java HotSpot(TM) Client VM (build
1.5.0_30-161, mixed mode, sharing)
Ubuntu: Ubuntu 12.04 PPC + OpenJDK Zero VM (build 22.0-b10, interpreted mode) (
1.7)
The original code can be found in Bruce Eckel's TIJ book (3rd ed.) in Ch. 4. The program is supposed to show how garbage collection works and how to invoke garbage collection by using the finalize() method. The interesting thing is that the program has completely different behavior on different platforms. Perhaps someone more knowledgeable can clue me in as to what's happening as I'm curious. It seems that the algorithms for gc() might be different in the JDKs, as the output is as follows.
OS X: It never gets out of the while loop and just keeps creating more Chair objects so you have to force quit it.
Chair 5760000 created.
Finalizing chair 5730000
Ubuntu: Cleans up Chair 47 after creating a lot of Chairs.
Finalizing Chair #47, Setting flag to stop Chair creation
After all Chairs have been created:
total created = 342919, total finalized = 64472
In his TIJ book, Mr. Eckel says:
The above program creates many Chair objects, and at some point after the garbage collector begins running, the program stops creating Chairs.
It seems that in OS X (my installation of course) the gc starts cleanup at the top of the heap, and as objects are added it can't keep up with cleanup and never gets to the bottom to get rid of Chair 47. In Ubuntu, it finally gets to Chair 47 somehow, even though it created more than 342k of them. I had the program running on OS X for 5 minutes and it never got rid of no. 47.
So, is the gc unstable because of the JDK, the OS, or the underlying architecture? Just out of curiosity.
And the code: