Java resource closing

后端 未结 8 1446
一生所求
一生所求 2021-01-12 00:57

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         


        
8条回答
  •  执念已碎
    2021-01-12 01:20

    BufferedReader br = null;
    

    You are declaring a variable without assigning it (null doesn't count - it is a useless assignment in this case). This is a code "smell" in Java (ref Effective Java; Code Complete for more on variable declaration).

    }finally{
        br.close();
        isr.close();
    }
    

    First, you only need to close the top-most stream decorator (br will close isr). Secondly, if br.close() threw an exception, isr.close() would not be called, so this is not sound code. Under certain exception conditions, your code will hide the originating exception with a NullPointerException.

    isr = new InputStreamReader(connection.getInputStream());
    

    If the (admittedly unlikely) event that the InputStreamReader constructor threw any kind of runtime exception, the stream from the connection would not be closed.

    Make use of the Closeable interface to reduce redundancy.

    Here is how I would write your code:

    URLConnection connection = new URL("www.example.com").openConnection();
    InputStream in = connection.getInputStream();
    Closeable resource = in;
    try {
      InputStreamReader isr = new InputStreamReader(in);
      resource = isr;
      BufferedReader br = new BufferedReader(isr);
      resource = br;
      String response = br.readLine();
    } finally {
      resource.close();
    }
    

    Note that:

    • no matter what kind of exception is thrown (runtime or checked) or where, the code does not leak stream resources
    • there is no catch block; exceptions should be passed up to where the code can make a sensible decision about error handling; if this method was the right place, you'd surround all of the above with try/catch

    A while back, I spent some time thinking about how to avoid leaking resources/data when things go wrong.

提交回复
热议问题