Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of overriding the finalize() method of Object class?

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?

like image 430
Rahul Avatar asked Apr 12 '11 13:04

Rahul


3 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:

  1. finalize is about memory and only memory.
  2. 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().

like image 177
Tadeusz Kopec for Ukraine Avatar answered Sep 28 '22 10:09

Tadeusz Kopec for Ukraine


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.

like image 37
Puce Avatar answered Sep 28 '22 10:09

Puce


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".

like image 24
McGlone Avatar answered Sep 28 '22 09:09

McGlone