finalize : Java Glossary

*0-9ABCDEFGHIJKLMNOPQRSTUVWXYZ (all)

finalize
Note the z. The American spelling is finalize. Java has all sorts of mechanisms for running special initialisation code, but it is rather weak on dealing with finalisation code. You can add a method called finalize to any class.
protected void finalize() throws Throwable {...}

When an object is about to be garbage collected, its finalize method will be run. The catch is, at shutdown, by default the finalizers are not run on all unreachable objects, so you can’t count on them to do things like close files.

// Force finalize methods to be run on exit
// Without this, unreachable objects may not
// have had finalize run when you quit.
System.runFinalizersOnExit( true );

Under no circumstances are finalizers run on reachable objects, so you can’t use them to close files for example.

You can arrange for a bit of code to be run on shutdown.

Runtime.getRuntime().addShutdownHook( new Thread()
            {
            public void run()
                {
                // stuff to do on shutdown
                }
            });

Unfortunately, addShutdownHook takes a memory-hogging Thread rather than a lightweight Runnable. The other problem is if you have two hooks, they will run simultaneously, interleaved. You will likely want to arrange all your work to be done from a single hook.

Some feel finalize should be deprecated and you should use phantom references instead since they give much better performance. Finalizers interfere with garbage collection. Their main use is debugging. Use them to issue an error message is an object is garbage collected without its close(), dispose(), disconnect()… method being called.


This page is posted
on the web at:

http://mindprod.com/jgloss/finalize.html

Optional Replicator mirror
of mindprod.com
on local hard disk J:

J:\mindprod\jgloss\finalize.html
Canadian Mind Products
Please the feedback from other visitors, or your own feedback about the site.
Contact Roedy. Please feel free to link to this page without explicit permission.

IP:[65.110.21.43]
Your face IP:[3.145.47.130]
You are visitor number