Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #30492

Re: finalize() not called.

From Eric Sosman <esosman@comcast-dot-net.invalid>
Newsgroups comp.lang.java.programmer
Subject Re: finalize() not called.
Date 2014-12-06 16:07 -0500
Organization A noiseless patient Spider
Message-ID <m5vr5r$h2m$1@dont-email.me> (permalink)
References <850b3ab9-57ea-490c-a165-943183169841@googlegroups.com>

Show all headers | View raw


On 12/4/2014 11:56 AM, somenathpal@gmail.com wrote:
> I have the following class
> public class Book {
> [...]
> 	protected  void  finalize() {
> 		if (checkout) {
> 			System.out.println("Error Checked Out !!");
> 		}
> 		
> 	}
> }

     Others have explained why finalize() will not be called when
you expect.  However, if you decide to implement finalize() for
this or any other class, you must obey its contract by ensuring
that the superclass' finalize() also runs:

	protected void finalize() throws Throwable {
	    try {
	        if (checkout) {
	            System.out.println("Error Checked Out !!");
	        }
	    } finally {
	        super.finalize();
	    }
	}

The try/finally block guarantees that super.finalize() will run
even if your own finalizer's operations throw an exception or
terminate abruptly.  Also, since the superclass' finalize() can
throw any Throwable, your finalize() must also be declared as
throwing Throwable.

     "Effective Java" by Joshua Bloch advises against implementing
finalize() at all, but shows how to do it properly (as above) and
even how to do it defensively (see the book) if you must.  I'll
second Volker Borchert's recommendation that you read this book;
it's a good 'un.

-- 
esosman@comcast-dot-net.invalid
"Don't be afraid of work. Make work afraid of you." -- TLM

Back to comp.lang.java.programmer | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

finalize() not called. somenathpal@gmail.com - 2014-12-04 08:56 -0800
  Re: finalize() not called. Robert Klemme <shortcutter@googlemail.com> - 2014-12-04 20:37 +0100
  Re: finalize() not called. v_borchert@despammed.com (Volker Borchert) - 2014-12-04 19:05 +0000
  Re: finalize() not called. Joshua Cranmer 🐧 <Pidgeot18@verizon.invalid> - 2014-12-04 14:24 -0600
  Re: finalize() not called. Eric Sosman <esosman@comcast-dot-net.invalid> - 2014-12-06 16:07 -0500
    Re: finalize() not called. Lew <lewbloch@gmail.com> - 2015-01-04 16:13 -0800

csiph-web