Basics of try-with-resources statement

Introduction

-Shows a description example when the try-with-resources statement is used and when it is not used. · Provides links to websites that are useful for understanding try-with-resources statements. -The try-with-resources statement can be used in Java SE 7 or later. -The classes that the try-with-resources statement can use are limited to the implementation classes of the AutoCloseable interface and its subinterface Closeable interface.

Description example of try-with-resources statement

Without the try-with-resources statement

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

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

        String inFilePath = "D:\\A.txt";
        String outFilePath = "D:\\C.txt";

        FileInputStream in = null;
        FileOutputStream out = null;

        try {
            in = new FileInputStream(inFilePath);
            out = new FileOutputStream(outFilePath);
            int c;

            //Copy the data
            while ((c = in.read()) != -1) {
                out.write(c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

point

    1. Even if there is no finally clause, a compile error does not occur, so there is a risk of resource release leakage.
  1. Variables are declared outside of try-catch-finally because both the try and finally clauses need to point to the same resource.
    1. Nesting of try-catch is required because there is a possibility of IOException in calling the close method of the finally clause.

When using the try-with-resources statement

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

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

        String inFilePath = "D:\\A.txt";
        String outFilePath = "D:\\C.txt";

        try (FileInputStream in = new FileInputStream(inFilePath);
                FileOutputStream out = new FileOutputStream(outFilePath);) {
            int c;

            //Copy the data
            while ((c = in.read()) != -1) {
                out.write(c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

point

    1. Basically, resources are automatically released. [^ 1] [^ 1]: Pattern where resources are not released by try-with-resources
  1. The scope of the variable is limited to the try clause.

    1. Exceptions at close are basically unnecessary to consider.

Reference site

Oracle Java SE Documentation try-with-resources statement TASK NOTES [Java] try-with-resources syntax try-catch-finally, try-with-resources, and exceptions that occurred

By the way

Classes such as FileInputStream call close in the finalize method, so it's hard to notice (and unlikely) the bug of resource release leaks. However, leaving the opening to the GC is inefficient and not a good practice, so use try-with-resources.

FileInputStream.java


package java.io;

import java.nio.channels.FileChannel;
import sun.nio.ch.FileChannelImpl;


public
class FileInputStream extends InputStream
{

===========================abridgement===========================

    /**
     * Closes this file input stream and releases any system resources
     * associated with the stream.
     *
     * <p> If this stream has an associated channel then the channel is closed
     * as well.
     *
     * @exception  IOException  if an I/O error occurs.
     *
     * @revised 1.4
     * @spec JSR-51
     */
    public void close() throws IOException {
        synchronized (closeLock) {
            if (closed) {
                return;
            }
            closed = true;
        }
        if (channel != null) {
           channel.close();
        }

        fd.closeAll(new Closeable() {
            public void close() throws IOException {
               close0();
           }
        });
    }

===========================abridgement===========================

    /**
     * Ensures that the <code>close</code> method of this file input stream is
     * called when there are no more references to it.
     *
     * @exception  IOException  if an I/O error occurs.
     * @see        java.io.FileInputStream#close()
     */
    protected void finalize() throws IOException {
        if ((fd != null) &&  (fd != FileDescriptor.in)) {
            /* if fd is shared, the references in FileDescriptor
             * will ensure that finalizer is only called when
             * safe to do so. All references using the fd have
             * become unreachable. We can call close()
             */
            close();
        }
    }
}

Recommended Posts

Basics of try-with-resources statement
Basics of Ruby
Basics of java basics ② ~ if statement and switch statement ~
[Rails] Introduction of devise Basics
Docker monitoring-explaining the basics of basics-
[GCD] Basics of DispatchQueue class
Basics of character operation (java)
[Practice! 】 Execution of SQL statement
Understand the basics of docker
Java programming basics practice-for statement
Summary of Java language basics
Java programming basics practice-switch statement
Basics of conditional branching and return
About the basics of Android development
Basics of sending Gmail in Ruby
The basics of SpringBoot + MyBatis + MySQL
Basics of Ruby ~ Review of confusing parts ~
Ruby Basics 2 ~ Review of confusing parts ~
[Ruby basics] About the role of true and break in the while statement
[Challenge CircleCI from 0] Learn the basics of CircleCI
Understand the basics of Android Audio Record
Memorandum of new graduate SES [Java basics]
[GCD] Basics of parallel programming in Swift
Now, I've summarized the basics of RecyclerView
[# 1 Java] Basics of Java-Major premise before studying-
[day: 5] I summarized the basics of Java
[Ruby] if statement concept of conditional expression
Looking back on the basics of Java
Rails Basics of creating a new application