Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't `loadFont` close input stream? Should I close it?

Looking at the documentation of Font#loadFont I came across this remark:

This method does not close the input stream.

Unfortunately, this is not explained or expanded upon. So my question is:

  1. What are possible reasons the API won't close the input stream? Is it likely you would like to re-use the stream? I mostly use this method like this:

    Font.loadFont(getClass().getResourceAsStream("path/to/font"), 13.0); 
    

    to make sure the font is available for my application, so I never re-use the input stream, and I can't really think of a reason I'd want to.

  2. Should I close the input stream myself? Should I expect any problems if I'm not closing the input stream? In the past I've had problems with a font loaded this way, where some labels configured with this font started showing squares, while others (on the same scene!) kept working fine. Could this be related to not closing the input stream?
like image 746
Itai Avatar asked Nov 08 '22 12:11

Itai


1 Answers

The documentation for every API involving scarce or external resources (such as file descriptors or streams) will make it clear whose responsibility it is to clean up (in this case, close the stream). This is sometimes referred to as "ownership".

In this case the documentation states that the loadFont method does not take ownership of the stream. Therefore it still belongs to you: It is your responsibility to close the stream.

The try-with-resources statement is the best way to do this.

like image 87
Ben Avatar answered Nov 15 '22 12:11

Ben