• Post Reply Bookmark Topic Watch Topic
  • New Topic

Object finalize () method  RSS feed

 
Gisele Mariana
Greenhorn
Posts: 7
Firefox Browser Java Notepad
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is object finalize method actually does?
I saw in documentation that it is a garbage collector,
Should i use it frequently?
 
Stevens Miller
Bartender
Posts: 1445
30
C++ Java Netbeans IDE Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In "Effective Java," Joshua Bloch wrote: Avoid finalizers.
Finalizers are unpredictable, often dangerous, and generally unnecessary.

They are not garbage collectors. Rather, the garbage collector will call an instance's finalize method after the Java virtual machine has determined that the instance is no longer accessible by any thread (roughly, when there are no more stored references to it). It is supposed to give you a chance to do your last-minute clean-up after you are done with an instance, but you'll generally have done that sort of thing as part of the path that leads to there being no more references to that instance anyway.

In short: ignore it and don't use it.
 
Ryan Gabriel
Greenhorn
Posts: 20
Android Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The finalize() method is actually a Hook method.
A Hook method is a method that there is an empty implementation provided in the Class Object and the idea is that when you want this method to be used you would provide an implementation in your own class by overriding this method and then this method will be called by the JVM.
Here, You can find out more about finalize method here.

As "Stevens Miller" referred about-
In "Effective Java," Joshua Bloch wrote:Avoid finalizers.
Finalizers are unpredictable, often dangerous, and generally unnecessary


the answer to your question is no, you should not use it frequently, not even once.
 
A.J. Côté
Ranch Hand
Posts: 417
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan Gabriel wrote:The finalize() method is actually a Hook method.
A Hook method is a method that there is an empty implementation provided in the Class Object and the idea is that when you want this method to be used you would provide an implementation in your own class by overriding this method and then this method will be called by the JVM.
Here, You can find out more about finalize method here.

As "Stevens Miller" referred about-
In "Effective Java," Joshua Bloch wrote:Avoid finalizers.
Finalizers are unpredictable, often dangerous, and generally unnecessary


the answer to your question is no, you should not use it frequently, not even once.


It is typical to ALWAYS use finalize to make sure a connection, thread or anything poolable is returned to its pool when there is no more reference to the wrapper object wrapping the real poolable object, more precisely when the jvm decides it is time to call finalize on the wrapper object because there is no more reference pointing to it.
 
A.J. Côté
Ranch Hand
Posts: 417
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is a typical usage of finalize in java.io.FileInputStream, make sure you close the file at the OS level if there is no more reference to the object. Of course, we should always close files, connections and return objects to pools ourselves because the jvm might take a long time after no more reference exists to actually call finalize but finalize was designed as a safeguard and should always be used in those situations. This is actually best practice to do that.

 
Stevens Miller
Bartender
Posts: 1445
30
C++ Java Netbeans IDE Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A.J. Côté wrote:Here is a typical usage of finalize in java.io.FileInputStream, make sure you close the file at the OS level if there is no more reference to the object. Of course, we should always close files, connections and return objects to pools ourselves because the jvm might take a long time after no more reference exists to actually call finalize but finalize was designed as a safeguard and should always be used in those situations. This is actually best practice to do that.


I'm afraid I have to disagree. java.io.FileInputSteam goes back to Java 1.0. There are a lot of things you'll find in code from that era that we wouldn't do today (consider Thread.stop, for example). It's true that some resources (as far as I know, always system-specific ones) can't be managed by Java. If you ask for one (a Windows graphics resource, for example), the host OS has no way of knowing that your application no longer has any instances of objects holding references to it. Thus, the JVM can't do for those resources what it does for objects that have no references: garbage-collect them. You have to return them to the OS yourself. But, that really means you have to pay close attention to which instances you allow to keep references to those system resources, and release those references when you know it is safe to do so. If you use a finalizer to do it, you run the big risk of releasing a reference that some other instance still needs. Just because a Java object is ready for garbage collection is no guarantee that all resources it holds references to are ready for garbage collection. Even in the source code you have posted, you can see the programmers were concerned about whether or not "[a]ll references using the fd have become unreachable[.]" That's not a trivial consideration. If the finalizer can't determine that (or the programmer doesn't know how to code the finalizer so it can determine that), it's going to release a resource some other instance still needs. And the odds of figuring out how that resource "vanished" from an application as a side-effect of another instance's being garbage-collected strike me as, well... unfavorable.

If you have a citation to a current text that supports the idea that releasing system resources in finalizers is a "best practice," I'd really like to read it. For now, I'm taking Bloch's advice, and urging new Java programmers to join me in it: avoid finalizers.
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And by the way, AJC, why do you have those three assertions in your signature? This is the beginning forum and there are likely to be people here who will believe all three of them.
 
A.J. Côté
Ranch Hand
Posts: 417
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:And by the way, AJC, why do you have those three assertions in your signature? This is the beginning forum and there are likely to be people here who will believe all three of them.


I just want to show that I am trying to adapt to the main stream java ranch mentality ! ;-) I am thinking of adding: finalizers are bad, understanding your code is bad!
 
A.J. Côté
Ranch Hand
Posts: 417
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stevens Miller wrote:

If you have a citation to a current text that supports the idea that releasing system resources in finalizers is a "best practice," I'd really like to read it. For now, I'm taking Bloch's advice, and urging new Java programmers to join me in it: avoid finalizers.


Of course, never rely on finalizers to accomplish a task. They are designed as a safeguard, but suggesting never to use them because you have to understand what you are doing strikes me. What other alternative do you suggest to implement that safeguard??

Additionally, here are the finalizers in jdk8. You will notice that some are much more recent than 1.0...


./javax/swing/text/StringContent.java: protected void finalize() throws Throwable {
./javax/imageio/spi/ServiceRegistry.java: public void finalize() throws Throwable {
./javax/imageio/spi/ServiceRegistry.java: public void finalize() {
./javax/imageio/stream/FileCacheImageInputStream.java: protected void finalize() throws Throwable {
./javax/imageio/stream/FileImageOutputStream.java: protected void finalize() throws Throwable {
./javax/imageio/stream/FileImageInputStream.java: protected void finalize() throws Throwable {
./javax/imageio/stream/MemoryCacheImageInputStream.java: protected void finalize() throws Throwable {
./javax/imageio/stream/ImageInputStreamImpl.java: protected void finalize() throws Throwable {
./java/util/concurrent/ThreadPoolExecutor.java: protected void finalize() {
./java/util/concurrent/Executors.java: protected void finalize() {
./java/util/zip/Deflater.java: protected void finalize() {
./java/util/zip/ZipFile.java: protected void finalize() throws Throwable {
./java/util/zip/ZipFile.java: protected void finalize() throws IOException {
./java/util/zip/ZipFile.java: protected void finalize() {
./java/util/zip/Inflater.java: protected void finalize() {
./java/util/Timer.java: protected void finalize() throws Throwable {
./java/lang/Enum.java: protected final void finalize() { }
./java/lang/ClassLoader.java: protected void finalize() {
./java/lang/Object.java: protected void finalize() throws Throwable { }
./java/awt/PrintJob.java: public void finalize() {
./java/awt/image/IndexColorModel.java: public void finalize() {
./java/awt/image/ColorModel.java: public void finalize() {
./java/awt/Graphics.java: public void finalize() {
./java/net/SocketInputStream.java: protected void finalize() {}
./java/net/AbstractPlainDatagramSocketImpl.java: protected void finalize() {
./java/net/SocketOutputStream.java: protected void finalize() {}
./java/net/AbstractPlainSocketImpl.java: protected void finalize() throws IOException {
./java/io/FileOutputStream.java: protected void finalize() throws IOException {
./java/io/FileInputStream.java: protected void finalize() throws IOException {
./com/sun/imageio/plugins/common/SubImageInputStream.java: protected void finalize() throws Throwable {
./com/sun/imageio/plugins/png/PNGImageWriter.java: protected void finalize() throws Throwable {
./com/sun/imageio/plugins/png/PNGImageWriter.java: protected void finalize() throws Throwable {
./com/sun/imageio/stream/StreamFinalizer.java: protected void finalize() throws Throwable {
./com/sun/jmx/snmp/SnmpPeer.java: protected void finalize() {
./com/sun/jmx/snmp/SnmpVarBindList.java: protected void finalize() {
./com/sun/jmx/snmp/daemon/SnmpSocket.java: protected synchronized void finalize() {
./com/sun/jmx/snmp/daemon/SnmpAdaptorServer.java: protected void finalize() {
./com/sun/jmx/snmp/daemon/SnmpInformRequest.java: protected void finalize() {
./com/sun/jmx/snmp/daemon/SnmpSession.java: protected void finalize() {
./com/sun/org/apache/xerces/internal/dom/CoreDocumentImpl.java: /*public void finalize() {
./com/sun/org/apache/xml/internal/resolver/readers/TextCatalogReader.java: protected void finalize() {

 
A.J. Côté
Ranch Hand
Posts: 417
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stevens Miller wrote:

If you have a citation to a current text that supports the idea that releasing system resources in finalizers is a "best practice," I'd really like to read it. For now, I'm taking Bloch's advice, and urging new Java programmers to join me in it: avoid finalizers.


Here, this dates from 2012, read it! That's about all there is to say about finalizers. Suggesting that they are bad and to never use them constitute a much too simplistic view ;-)

http://javarevisited.blogspot.ca/2012/03/finalize-method-in-java-tutorial.html
 
Knute Snortum
Sheriff
Posts: 4274
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This current discussion does not belong in Beginning Java. Please continue it in a more appropriate forum.
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A.J. Côté wrote:. . .Here, this dates from 2012, read it! That's about all there is to say about finalizers. Suggesting that they are bad and to never use them constitute a much too simplistic view . . .
But that link hardly recommends you ever to use finalize().

As Knute suggests, I shall move this discussion.
 
Roel De Nijs
Sheriff
Posts: 11338
177
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A.J. Côté wrote:It is typical to ALWAYS use finalize to make sure a connection, thread or anything poolable is returned to its pool when there is no more reference to the wrapper object wrapping the real poolable object, more precisely when the jvm decides it is time to call finalize on the wrapper object because there is no more reference pointing to it.

Typical You have to be kidding! I've been developing Java applications for over more than 10 years and have NEVER used the finalize() method. Maybe once or twice in some test code to confirm how unpredictable this method really is. And to prove how unpredictable this method really is, here is a very simple code snippetWhen I run this application on my computer, I expect to see 10x "in finalize", but there was no output at all. When I incremented the number of iterations to 1000, 10_000 and even 100_000, still no output. When incremented to 1_000_000, a bunch of "in finalize" were printed (but definitely not 1_000_000). When you run this on your own computer, the results might be different.

A.J. Côté wrote:Additionally, here are the finalizers in jdk8. You will notice that some are much more recent than 1.0...

That's a very nice list, but that doesn't prove anything. These JDK8 classes implement the finalize() method as some kind of last safety net. A last attempt to prevent resource leaks as some kind of convenience for developers who don't close their resources as it should be. But a good developer will always close the resource (file, connection,...) once he's done using it. So for a good developer it doesn't matter that finalize() method of e.g. FileInputStream is implemented or not, the resource will already be closed (and thus finalize() could be empty as well)!

So don't use the finalize() method: it's really unpredictable (as the above code snippet illustrates) and it's really unnecessary as well (as there are waay better alternatives, e.g. try-with-resources and Automatic Resource Management in Java 7)

Just my 2 cents!
Kind regards,
Roel
 
A.J. Côté
Ranch Hand
Posts: 417
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roel De Nijs wrote:
A.J. Côté wrote:It is typical to ALWAYS use finalize to make sure a connection, thread or anything poolable is returned to its pool when there is no more reference to the wrapper object wrapping the real poolable object, more precisely when the jvm decides it is time to call finalize on the wrapper object because there is no more reference pointing to it.

Typical You have to be kidding! I've been developing Java applications for over more than 10 years and have NEVER used the finalize() method. Maybe once or twice in some test code to confirm how unpredictable this method really is. And to prove how unpredictable this method really is, here is a very simple code snippetWhen I run this application on my computer, I expect to see 10x "in finalize", but there was no output at all. When I incremented the number of iterations to 1000, 10_000 and even 100_000, still no output. When incremented to 1_000_000, a bunch of "in finalize" were printed (but definitely not 1_000_000). When you run this on your own computer, the results might be different.



Here, try to run this code, it should give you the results you expect! If not, add more memory consuming code to give an opportunity to the jvm to call finalize() before your program terminates. This is how finalizers work.



 
Roel De Nijs
Sheriff
Posts: 11338
177
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A.J. Côté wrote:If not, add more memory consuming code to give an opportunity to the jvm to call finalize() before your program terminates. This is how finalizers work.

That's a very nice example, but it still doesn't cover the unpredictability of this method being executed or not. And you could add all the memory consuming code you want, but if your program uses/relies on finalize() to get some task done and GC doesn't kick in, you're toast! So why spend time in implementing a method of which you have no guarantee it will be executed at all
 
A.J. Côté
Ranch Hand
Posts: 417
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roel De Nijs wrote:
A.J. Côté wrote:If not, add more memory consuming code to give an opportunity to the jvm to call finalize() before your program terminates. This is how finalizers work.

That's a very nice example, but it still doesn't cover the unpredictability of this method being executed or not. And you could add all the memory consuming code you want, but if your program uses/relies on finalize() to get some task done and GC doesn't kick in, you're toast! So why spend time in implementing a method of which you have no guarantee it will be executed at all


As explained here, it is a nice to have safety net:
http://www.informit.com/articles/article.aspx?p=1216151&seqNum=7
 
Roel De Nijs
Sheriff
Posts: 11338
177
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A.J. Côté wrote:It is typical to ALWAYS use finalize

A.J. Côté wrote:As explained here, it is a nice to have safety net

Are you not contradicting yourself? Because "ALWAYS" suggests having a finalize() method as a must-have. And now it's already degraded to an (optional) nice-to-have.
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A.J. Côté wrote:As explained here, it is a nice to have safety net:
http://www.informit.com/articles/article.aspx?p=1216151&seqNum=7

Well, a safety net is definitely a nice to have. However, I am not sure that something that may or may not run, meaning something that may or may not work, should be considered a safety net...

Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!