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.
Without lots more info it's not possible to explain the results you have seen. There isn't just a universal "garbage collector", there are many different algorithms that can be used for garbage collection.
It is possible the two systems are using different GC algorithms, it is also possible the trigger points are different on the two systems, for example if there are different amounts of available memory etc. Also there is no guarantee when a finalize method will be called or even it if it will be called at all - see this article http://javarevisited.blogspot.co.uk/2012/03/finalize-method-in-java-tutorial.html
Seems the gc is a bit unpredictable, but saves us from memory management at least.
Joined: Aug 07, 2007
I don't think unpredictable is the correct term because once you know all the parameters that effect the GC cycle I'm sure it is predictable. The problem is that these vary from setup to setup.
And yes having a GC saves us programmers effort and prevents some difficult to find bugs in most cases.