Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

resource warn java

Eclipse(Juno) says there is a resource leak warnings in this sample. Is this valid?
This is occurred when the exception throwing point is in the for loop.

package kuni;

import java.io.FileWriter;
import java.util.Arrays;

public class ResourceWarn {
    public static void main(String[] args){

        try {
            FileWriter f = null;
            try{
                f = new FileWriter("test.txt");
                for(String s : Arrays.asList("a","b","c")){
                    if(s.equals("c"))throw new RuntimeException("aa"); //resource leak warn here
                    f.write(s);
                }
            }finally{
                try{
                    f.close();
                }catch(Exception ignore){
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
like image 646
user2074126 Avatar asked Nov 26 '25 19:11

user2074126


2 Answers

I think I know what Eclipse is complaining about.

        } finally {
            try {
                System.err.println("closing f");
                f.close();
            } catch(Exception ignore) {
            }
        }

The problem is the println !!!

Eclipse thinks that it is possible that the System.err.println(...) call could throw an exception. If that were to happen, then the f.close() call wouldn't happen .... ergo, a leak.

You and I know that this "can't happen" ... but the Eclipse code analyser probably doesn't understand the special nature of System.err.

And besides, it is possible that somewhere else in the code we've done something that would cause System.err.println(...) to fail; e.g. we might have used System.setErr(...) to replace the normal System.err instance with an instance of some custom PrintWriter subclass that throws an unchecked exception on the 2nd Tuesday of every month.

Try removing the println or moving it after the close call.

like image 174
Stephen C Avatar answered Nov 28 '25 07:11

Stephen C


No, you don't have a resource leak there. I don't know what eclipse is complaining of.

The only comments I have regarding your code are:

  1. It will be easier to read if you include spaces between keywords and opening/closing braces.

  2. You shouldn't throw away the IOException in the finally block, rather you should log it and continue (as you currently do). There are weird bugs that happen when cleanup code throws exceptions and logging religiously will save you extremely painful debugging sessions.

  3. For a demo like this, printing the stack trace is fine, but in general you should be logging it, and only printing a short error message to stderr. Users panic when they see stacktraces, even when benign.

Other than that, the code looks good to me, and none of the above suggest a resource leak.

like image 33
Recurse Avatar answered Nov 28 '25 07:11

Recurse