Re: When will finalize() be invoked?
In article <gin216$85c$2@news.motzarella.org>,
Mark Space <markspace@sbcglobal.net> wrote:
Nguyen Minh Hai wrote:
Then what is the purpose of introducing finalize() in Java?
Read Joshua Cramer's reply:
" Pretty much the only time you should be defining a finalize() method
is if you need to free memory associated with the object via native code. "
A common example is disposing of a graphics context that was created
directly, perhaps during offscreen drawing. The Graphics class
overrides finalize() to (eventually) free system resources by calling
dispose(); the latter may be invoked directly instead of waiting for
finalize() to be called:
<http://java.sun.com/javase/6/docs/api/java/awt/Graphics.html#dispose()>
<http://java.sun.com/javase/6/docs/api/java/awt/Graphics.html#finalize()>
For example:
<code>
private static final int SIZE = 128;
private static final Font FONT = new
Font("Serif", Font.BOLD, SIZE * 7 / 8);
private static final BufferedImage errorImage = new
BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_ARGB); {
Graphics2D g2d = errorImage.createGraphics();
g2d.setPaint(Color.red.darker());
g2d.setFont(FONT);
String s = "\u2298";
int w2 = g2d.getFontMetrics().stringWidth(s) / 2;
int h2 = g2d.getFontMetrics().getDescent();
g2d.drawString(s, SIZE / 2 - w2 , SIZE / 2 + h2);
g2d.dispose();
}
</code>
--
John B. Matthews
trashgod at gmail dot com
http://home.roadrunner.com/~jbmatthews/