Question from Mind Q Mock. 37. Which of the following statements about Java's garbage collection are true? a) The garbage collector can be invoked explicitly using a Runtime object. b) The finalize method is always called before an object is garbage collected. c) Any class that includes a finalize method should invoke its superclass' finalize method. d) Garbage collection behavior is very predictable. Ans is a, b, c. I don't think a and c qualify as being true. To me (a) does not seem true, because we only suggest garbage collection, we don't exactly invoke it. So how is (a) true? Secondly,I know that the finalize method does not implicitly call its superclasses finalize. So you could explicitly invoke superclass' finalize method, but its not rule that you should have to right? In that case (c) is not true. Am I right?
You're right - a is not correct. We can suggest that garbage collection run, but it isn't guaranteed that it will run. However, option c says that we "should" invoke the superclass' finalize method in the subclass' finalize method. It doesn't say that we "must" invoke it. As a general rule, it is good practice to invoke the superclass' finalize method should I would say that c is true - we should do it, but we don't have to. Corey
I can't say I am happy with options a and b in this question at all. a. although there is a runtime gc() method call, you can't be sure the garbage collector will run so I guess it depends on what you think "invoked" implies. b. running finalizers is separate from the actual garbage collection step and occurs after the GC mechanism has determined that an object is unreachable. c. I like as good programming practice so "should invoke" seems reasonable. d. It would be hard to defend this as true. Bill
Originally posted by Roger Chung-Wee: Is it true that the GC mechanism decides that GC should be done, invokes finalize and then garbage collects? If so, then is not b correct.
You will never find a case in which an object is garbage collected without its finalize method being invoked. The whole purpose of a finalize method is to allow the object to perform any "cleanup" needed prior to being destroyed. If the garbage collector didn't guarantee that this method would be invoked prior to collecting an object, we'd defeat the whole purpose of the method. Corey