Please could you tell me how many times finalize() method would be called of this class :
1. Exactly one time
2. One or two times
3. Exactly Two times
4. Can't say
When I run this code, it calls finalize() exactly one time as it gets called from the constructor (although it's incorrect to do so). However, can this method be called again before the garbage collection happens (in this case)? If so, what would be the correct answer. Thanks in advance.
Instance methods are never called on a class; they are called on objects. There is no guarantee that the GC process will run at all; if it does run it may not release a particular object, so the number of times finalize() runs is unpredictable. You would not have finalize() run 3× or more.
Where did you get that code from? It is the sort of thing that, if written at work, would guarantee you are looking for a new job
The answer is 2. "One or two times", though it almost always will be run just once. It will be run once definitely because you call it from the constructor. It may be called a second time because the object becomes unreachable in line 10, and therefore eligible for garbage collection. A hypothetical JVM that has a very aggressive garbage collector could run the finalizer as soon as the object becomes eligible.
Campbell Ritchie wrote:Instance methods are never called on a class; they are called on objects. There is no guarantee that the GC process will run at all; if it does run it may not release a particular object, so the number of times finalize() runs is unpredictable. You would not have finalize() run 3× or more.
Where did you get that code from? It is the sort of thing that, if written at work, would guarantee you are looking for a new job
Thanks for the explanation. I'm these days randomly doing such stuff and in turn trying to get a better understanding how things work in Java. Don't worry, it's not written at work as I'm a new mom and on a break doing weird stuff at home.