Why do we need an improved and appeared in JDK 7 statement try -c-resources?

 try (спецификация_ресурса) { //использование ресурса { 

    2 answers 2

    The try -c-resources operator implements the principle of automatic resource management , the purpose of which is to avoid, for example, memory leaks, in cases when a resource is not freed for some reason if it is no longer needed.

    The unsuccessful outcome of closing a file can lead to "memory leaks", since unused RAM resources will remain allocated. ( P. 365 )

     try ( FileInputStream res = new FileInputStream(args[O])) { //использование ресурса } 

    The try -c-resources try allows you to declare and initialize a resource (in parentheses after the try ), creating a local context variable in the try block. Upon completion of this block, the variable is deleted, and therefore the resource is automatically closed.

    Hence, it is not necessary to close the resource explicitly using the close() method in the finally statement block.

    • Well, just not the memory, the memory collector monitors the memory. - Qwertiy
    • @Qwertiy if in the usual try to forget to close the resource there will be no memory leak, will the garbage collector work? - TimurVI
    • As far as I can imagine, only native resources can leak. Memory should still be cleared by the garbage collector. In the case of a file, an open handle with a lock on the file can remain - at least until the garbage collection (or rather I don’t know, I don’t really understand Java, but it’s up to Sharp, because the finalizer would clean up). - Qwertiy

    try-catch with resources was invented only to avoid templating code.

    Let's try to write, a simple method, to read the first line from a file. Before java 7, it would look like this:

     private static String readFirstLine(String fileName) { BufferedReader reader = null; String line = null; try { reader = new BufferedReader(new FileReader(fileName)); line = reader.readLine(); reader.close(); } catch (IOException e) { try { reader.close(); } catch (IOException e1) { e1.printStackTrace(); } } return line; } 

    We noticed that in the catch we need another block to handle exceptions, since we have to close the resource, but the closing operation in turn can also throw an exception.

    Do not forget that try-catch with resources allows you not to think about freeing resources. As soon as program execution leaves the scope of the resource / resources, they automatically call the java.lang.AutoCloseable.close() method.

    In fact, this construction can be represented as a method that takes as input a block of code that requires execution and a list of resources that must be released after its execution.

     private static void invoke(Callable<Void> task, Closeable... resources) throws Exception { Exception exception = null; try { task.call(); } catch (Exception e) { exception = e; } finally { for (Closeable closeable : resources) try { closeable.close(); } catch (Exception e) { if (exception == null) exception = e; else exception.addSuppressed(e); } } if (exception != null) throw exception; }