Bug 24378

Summary: Minor problem in sample code for embedding
Product: Fop - Now in Jira Reporter: Manuel Mall <mm>
Component: documentationAssignee: fop-dev
Status: NEW ---    
Severity: normal    
Priority: P3    
Version: all   
Target Milestone: ---   
Hardware: Other   
OS: other   

Description Manuel Mall 2003-11-04 09:11:22 UTC
The sample code on the FOP web site for embedding uses in a number of places 
constructs like

Driver driver = new Driver(new InputSource(args[0]),
                           new FileOutputStream(args[1]));

or

driver.setOutputStream(new FileOutputStream(args[1]));

Using "new ...Stream(...)" as a constructor or function argument is dangerous 
as the stream doesn't get closed until the object is garbage collected. This 
can lead to "out of file handle" conditions.

I learned this the hard way with a (supposedly) perfectly working server 
application which had fop embedded. The app ran happily for over two years. 
Then a hardware upgrade came along and the system admin changed the Java VM 
settings to give it more memory as the new machine had lots of it. Suddenly the 
system was running out of file handles because the Java VM did less garbage 
collection which in turn kept all those implicitly constructed streams open.

The sample code should probably be looking more like

FileOutputStream fos = new FileOutputStream(args[1]);
Driver driver = new Driver(new InputSource(args[0]), fos);
fos.close();

or to make sure the file is always closed like:

FileOutputStream fos = null;
try {
    fos = new FileOutputStream(args[1]);
    Driver driver = new Driver(new InputSource(args[0]), fos);
    fos.close();
} finally {
    if (fos != null) {
        try {
            fos.close();
        } catch (IOException ioe) {}
    }
}

which is probably an overkill for the sake of the example.