I've a hard time understanding the following:
"The Java language specification allows a dummy gc() method."
Why would the standard do this?
Its effectively making a very important feature of java optional.
This would also mean my same program will behave differently on two different JVM implementations !!! Something totally against Java's important feature of portability.
Its effectively making a very important feature of java optional.
The GC is not made optional by that in Java. What is made optional is an explicit garbage collection, triggered by a call to gc()
. And this is completely acceptable, since explicitly triggering a garbage collection is rarely necessary and interferes with the function of a modern garbage collector.
Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.
Calling gc()
is not guaranteed to trigger garbage-collection. I.e. you cant force garbage collection. That's why the method can be dummy.
"The best effort" mentioned above might be "waited for implicit garbage collection".
This would also mean my same program will behave differently on two different JVM implementations !!! Something totally against Java's important feature of portability.
Differences of this sort between different JVM implementations is actually a good thing. It allows improvements in the underlying details that don't affect the correctness of a program and usually improve performance. Garbage collection happens to be an area where the JVM spec focuses on allowing implementation room to basically experiment with different approaches to solving the problem. Sun explicitly states that calling gc() will not force a memory sweep, so programmers can not make the claim that they expect a certain behavior out of every JVM.
The core idea - gc() is optional and you can force to collect garbage if you want.
But still you have the "automatic" garbage collection as it should be. gc() is just a matter of making a program more and more effective
It is usually a good idea to let the JVM figure out when it needs to do garbage collection instead of explicitly telling it to do so. The fact that the Java spec allows a dummy method does not change the fact that Java does garbage collection, it just means that it can ignore requests from you to do it explicitly.
Here is a good (slightly old) article about garbage collection in Java, which has a short paragraph on System.gc(): http://www.ibm.com/developerworks/library/j-jtp01274.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With