As far as I know , in java if we want to manually call the garbage collector we can do System.gc().
1.What are the operations that we do inside our overriden finalize() method?
2.Is it required to override the finalize() method if we want to manually call the JVM garbage collector?

- 89
- 1
- 1
- 7
-
2most likely you will never need finalize() besides logging to trace leaks, keep in mind finalize() slows down (considerably) the objects and requires synchronization to be implemented properly. – bestsss Apr 12 '11 at 14:07
-
And notice that your `finalize()` method, if called, wil be called only once. – reef Aug 28 '13 at 09:26
-
1here you assume System.gc() allows manual GC. Actually it is not "manual" in the sense JVM might or not not follow this request. This call is just a hint to the VM. – PoweredByRice Mar 27 '14 at 17:07
8 Answers
What are the operations that we do inside our overriden finalize() method?
Free memory alocated manually (through some native calls) i.e. not managed by GC. It is a really rare situation.
Some people put there also a check, that other resources connected with the object have already been released - but it's only for debugging purposes and it's not very reliable.
You must remember that:
finalize
is about memory and only memory.- You have no control when it will be invoked and even whether it be invoked.
So never ever put there releasing any other resources (like file handles, locks). All those resources must be released manually.
And overriding finalize has nothing to do with calling System.gc()
.

- 12,283
- 6
- 56
- 83
Others already explained the finalize method.
Note however, that best practices is to design a "close"/ "clean-up"/ "termination" method to close/ clean-up the object and ask the developer to call this method explicitly. Finalizers should only be used as a safety net. (See "Item 7: Avoid finalizers" of "Effective Java" by Joshua Bloch)
Update:
In this case also consider to implement AutoCloseable to support try-with-resources blocks.

- 37,247
- 13
- 80
- 152
Overriding the finalize method is often done if you need to manually release resources (particularly those that would use large amounts of memory or cause locks, if they weren't released). For example, if you have an object that has a lock on a file or database table, you may want to override your finalize method in order to release those objects for use when your object is garbage collected.
As for whether or not overriding finalize is required, it absolutely is not. You can call System.gc() without ever overriding a finalize method. One word of caution, though - calling System.gc() doesn't absolutely dictate that the garbage collector will do anything. Consider it more of a "recommendation" to the JVM to run garbage collection, as opposed to a "mandate".

- 3,434
- 5
- 26
- 31
-
2The only thing I would add is that you should try as hard as possible to release all resources without ever using `finalize()` since it can hurt performance, and there are no guarantees about when it will actually get called – Adam Batkin Apr 12 '11 at 13:24
-
1I agree with Adam for a couple reasons. Indeed, using finalize can hurt your performance, but it's difficult to use due to the fact that you never really know when it will be called. Garbage collection is done on its own schedule and, even if you call System.gc(), you can't *force* it to happen. As such, releasing resources in your finalize method can lead to all sorts of odd things happening because it's more difficult to follow the flow of your application. I'd strongly suggest releasing resources as soon and as explicitly as possible in order to make your life easier. – McGlone Apr 12 '11 at 13:28
-
Thanks a lot for the response...If I override the finalize() in my class then how to call that method?? Or JVM itself at the time of garbage collection will call my overriden finailze()?? – Rahul Apr 20 '11 at 07:57
-
1You can call it just like any other instance method. That said, the whole purpose behind the finalize method is that you don't have to call it. When the JVM executes its garbage collection process, it'll call finalize on every object it intends to garbage collect. The JVM will invoke your finalize method only one time, ever. However, if you are invoking it directly, you can invoke it as many times as you'd like. If you intend to invoke the method yourself, don't use finalize - just make a method and use it. Use finalize if you want to leverage the garbage collector. – McGlone Apr 21 '11 at 19:08
For very rare cases it may be useful or necessary to implement finalize
for freeing allocated resources. This method is always called when an instance is destroyed finally.
May be helpful if you work with native code and need to free allocated resources in the native code area.
But use it with care, because implementing finally
will slow down the garbage collector dramatically and kill performance.

- 113,398
- 19
- 180
- 268
-
1Finalize slows down the allocation (the object is added to a linked list before the c-tor is called), not the garbage collection. finalize() is executed in a separate thread as well. – bestsss Apr 12 '11 at 14:02
1) Any clean up that you want to do on object destruction (if you keep some handles open and nobody has called an explicit close for example). Keep in mind that you don't know when this will happen because the JVM will call the GC and not you.
2) Nope.
Side note, you should not manually call the Garbage Collector, see the answer here, Why do you not explicitly call finalize() or start the garbage collector?
-
I keep hearing that there is no guarantee that finalize() will be called, but how likely is it that Java will not call finalize() for an object in a long-running program except for perhaps cases where the JVM shutdown before it gets around to it? ...or should this be a separate question? – Sled Apr 12 '11 at 13:24
-
1It will get called at least once. Well, I reported a bug to JBoss last year because I was running out of file handles. They were closing their File resources in the finalize() method and I ran out before a finalize was called. It boils down to app size, memory settings and alignment of the planets. It is good to keep in mind that it might not happen and maybe an explicit close is better. – toomasr Apr 12 '11 at 13:40
-
1No. It may be never called. And releasing handles in `finalize` method is a programming erro. They should be reelased manually when they are no longer needed (`try finally` is for cleaning resources) – Tadeusz Kopec for Ukraine Apr 12 '11 at 14:05
-
1@Tadeusz wow, actually you are correct. Went through java.lang.Shutdown, you have to explicitly tell the JVM to get finalizers run on exit. So they might not get called at all! – toomasr Apr 12 '11 at 15:01
-
But how likely is it? If I am writing a Java Swing app (lets say an IDE) and the user is close the application and the syustems resources aren't going to be maxed etc etc in this kind of scenario are finalizers near guaranteed to get run? – Sled Apr 12 '11 at 15:13
-
1The ones that are between last GC and the shutdown won't run. See System.runFinalizersOnExit() javadoc, they used to allow that but now marked as not safe and thus deprecated. – toomasr Apr 13 '11 at 07:00
There is no guarantee that the finalizer will be called promptly so you should not do anything critical in your finalize method.
- Release system resources (Such as IOStreams) as a safety net if they weren't already closed or released.
- Release system resources iin native code that the GC doesn't know about.

- 73,164
- 16
- 126
- 119
@Andreas_D: I agree with what reef says and what he implies is that, if finalize() contains code that makes the current instance ineligible for GC, i.e. brings it back to life by giving a live thread a reference to this instance, then the next time that that instance becomes eligible for GC, DO NOT expect finalize() to be called by the JVM again. As far as the JVM is concerned, it has done its duty by calling finalize() once and cannot be bothered to do it again and again just because you keep bringing the instance back to life again. If it did, then that object would never be GC'ed. (Of course, you might want the instance never to be GC'ed. Then just have a live thread maintain a reference to it. If no live thread has a reference to the instance, the instance is as good as dead, anyway.)

- 603
- 6
- 30
1.What are the operations that we do inside our overriden finalize() method?
Cleaning up resources that cannot be handled by garbage collection.
2.Is it required to override the finalize() method if we want to manually call the JVM garbage collector?
No, these two things are unrelated.
finalize should certainly not call the garbage collector itself. In fact, finalize is called by the garbage collector (but is not guaranteed to be called at all).

- 32,079
- 16
- 104
- 187