javajava.util.scannerresource-leak

Resource leak over String Scanner java


In vscode I get a warning saying that Scanner has a resource leak for scanning over a String, but String doesn't need to be closed, so why does vscode give me a warning and how can I get rid of it? I don't want to close the Scanner because that is not necessary. Here is some example code that gives the warning

new Scanner("somthing to split")
            .useDelimiter(Pattern.compile("[ ,\n]"))
            .forEachRemaining(System.out::println);

Gives Resource leak: '<unassigned Closeable value>' is not closed at this location


Solution

  • VSCode does not care what resource your Scanner is tied to. It does not check whether you actually should close it or not.

    Either suppress the warning, by adding @SuppressWarnings("resource") or close the scanner properly using try-with-resources syntax:

    try (Scanner scanner = new Scanner(...)) {
        ...
    } // auto-closed here
    

    Not all warnings are actually correct, there are false positives as well and it is totally okay to suppress a warning in such a case. You might want to add a comment to explain why though.

    Another related example are scanners tied to System.in, they should not be closed either.


    but won't this make it run slower? I'm trying to not close it because it is unnecessary but I don't want this warning

    No, not really. And even if, we would be talking about a few nanoseconds here. Dont try to micro-optimize something that does not have to be optimized at all. If you think you have a speed issue, profile your application and then you will notice that your offender is something completely different anyways.