Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java resource closing

I'm writing an app that connect to a website and read one line from it. I do it like this:

try{
        URLConnection connection = new URL("www.example.com").openConnection();
        BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String response = rd.readLine();
        rd.close();
    }catch (Exception e) {
        //exception handling
    }

Is it good? I mean, I close the BufferedReader in the last line, but I do not close the InputStreamReader. Should I create a standalone InputStreamReader from the connection.getInputStream, and a BufferedReader from the standalone InputStreamReader, than close all the two readers? I think it will be better to place the closing methods in the finally block like this:

InputStreamReader isr = null;
BufferedReader br = null;
try{
    URLConnection connection = new URL("www.example.com").openConnection();
    isr = new InputStreamReader(connection.getInputStream());
    br = new BufferedReader(isr);
    String response = br.readLine();
}catch (Exception e) {
    //exception handling
}finally{
    br.close();
    isr.close();
}

But it is ugly, because the closing methods can throw exception, so I have to handle or throw it.

Which solution is better? Or what would be the best solution?

like image 594
Bob Avatar asked Jun 15 '10 11:06

Bob


People also ask

Does try with resources automatically close?

The Java try with resources construct, AKA Java try-with-resources, is an exception handling mechanism that can automatically close resources like a Java InputStream or a JDBC Connection when you are done with them.

How does Java 7 handle closing of resources?

Support for try-with-resources — introduced in Java 7 — allows us to declare resources to be used in a try block with the assurance that the resources will be closed after the execution of that block. The resources declared need to implement the AutoCloseable interface.

Which is valid to close the resources automatically in Java?

automatic resource management or try-with-resources is a new exception handling mechanism that was introduced in Java 7, which automatically closes the resources used within the try-catch block.

Does try with resources close before finally?

In a try -with-resources statement, any catch or finally block is run after the resources declared have been closed.


2 Answers

The general idiom for resource acquisition and release in Java is:

final Resource resource = acquire();
try {
    use(resource);
} finally {
    resource.release();
}

Note:

  • try should immediately follow the acquire. This means you can't wrap it in the decorator and maintain safety (and removing spaces or putting things on one line doesn't help:).
  • One release per finally, otherwise it wont be exception safe.
  • Avoid null, use final. Otherwise you'll have messy code and potential for NPEs.
  • Generally there is no need to close the decorator unless it has a further resource associated with it. However, you will generally need to flush outputs, but avoid that in the exception case.
  • The exception should either be passed through to the caller, or caught from a surrounding try block (Java leads you astray here).

ou can abstract this nonsense with the Execute Around idiom, so you don't have to repeat yourself (just write a lot of boilerplate).

like image 170
Tom Hawtin - tackline Avatar answered Nov 02 '22 05:11

Tom Hawtin - tackline


Closing the BufferedReader is enough - this closes the underlying reader too.

Yishai posted a nice pattern for closing the streams (closing might throw another exception).

like image 24
Andreas Dolk Avatar answered Nov 02 '22 07:11

Andreas Dolk