KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > imageio > stream > StreamFinalizer


1 /*
2  * @(#)StreamFinalizer.java 1.1 05/11/23
3  *
4  * Copyright 2005 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package com.sun.imageio.stream;
9
10 import java.io.IOException JavaDoc;
11 import javax.imageio.stream.ImageInputStream JavaDoc;
12
13 /**
14  * Small class to assist in properly closing an ImageInputStream instance
15  * prior to garbage collection. The ImageInputStreamImpl class defines a
16  * finalize() method, but in a number of its public subclasses
17  * (e.g. FileImageInputStream) we override the finalize() method to be
18  * empty for performance reasons, and instead rely on the Disposer mechanism
19  * for closing/disposing resources. This is fine when one of these classes
20  * is instantiated directly (e.g. new FileImageInputStream()) but in the
21  * unlikely case where a user defines their own subclass of one of those
22  * streams, we need some way to get back to the behavior of
23  * ImageInputStreamImpl, which will call close() as part of finalization.
24  *
25  * Typically an Image{Input,Output}Stream will construct an instance of
26  * StreamFinalizer in its constructor if it detects that it has been
27  * subclassed by the user. The ImageInputStream instance will hold a
28  * reference to the StreamFinalizer, and the StreamFinalizer will hold a
29  * reference back to the ImageInputStream from which it was created. When
30  * both are no longer reachable, the StreamFinalizer.finalize() method will
31  * be called, which will take care of closing down the ImageInputStream.
32  *
33  * Clearly this is a bit of a hack, but it will likely only be used in the
34  * rarest of circumstances: when a user has subclassed one of the public
35  * stream classes. (It should be no worse than the old days when the public
36  * stream classes had non-empty finalize() methods.)
37  */

38 public class StreamFinalizer {
39     private ImageInputStream JavaDoc stream;
40
41     public StreamFinalizer(ImageInputStream JavaDoc stream) {
42         this.stream = stream;
43     }
44
45     protected void finalize() throws Throwable JavaDoc {
46         try {
47             stream.close();
48         } catch (IOException JavaDoc e) {
49         } finally {
50             stream = null;
51             super.finalize();
52         }
53     }
54 }
55
Popular Tags