Java Advanced Knowledge Point 3: Close resources more gracefully-try-with-resource syntax

Source: Internet
Author: User
Tags finally block getmessage throwable

We know that in Java programming, if external resources (files, database connections, network connections, and so on) are opened, we must close them manually after these external resources have been used. Because external resources are not managed by the JVM and are not able to enjoy the garbage collection mechanism of the JVM, if we do not ensure that external resources are closed at the right time during programming, the external resources will be compromised, and then there will be a lot of serious problems such as the file being used abnormally, and the connection pool overflow caused by too many database connections.

To ensure that external resources must be closed, the closing code is usually written to the finally block, and of course we have to notice the exceptions that might be thrown when the resource is closed, and then the following classic code is changed:

 Public Static voidMain (string[] args) {FileInputStream InputStream=NULL; Try{InputStream=NewFileInputStream (NewFile ("Test"));    System.out.println (Inputstream.read ()); } Catch(IOException e) {Throw Newruntimeexception (E.getmessage (), E); } finally {        if(InputStream! =NULL) {            Try{inputstream.close (); } Catch(IOException e) {Throw Newruntimeexception (E.getmessage (), E); }        }    }}

Friends who are familiar with other languages may start to spit out, in C + +, we can put the code that closes the resource in the destructor, in C #, we have a using code block. These syntaxes have a common feature that allows the closing behavior of an external resource to be associated with the life cycle of the external resource's handle object, and the shutdown behavior of the external resource is automatically invoked when the handle object life cycle of the external resource is terminated, such as when the handle object is scoped. This is not only more in line with the object-oriented programming concept (the behavior of closing external resources within the handle object of external resources), but also makes the code more concise and understandable. How to get to Java here, you can not find the automatic shutdown of external resources syntax features.

Indeed, before JDK7, Java did not automatically turn off the syntax characteristics of external resources until the Try-with-resource syntax was added to JDK7.

So what is Try-with-resource? In short, when a handle object of an external resource (such as a FileInputStream object) implements the Autocloseable interface, the above-mentioned plate code can be simplified to the following form:

 Public Static void Main (string[] args) {    trynew fileinputstream (new File ("test")){        System.out.println (Inputstream.read ());     Catch (IOException e) {        thrownew  runtimeexception (E.getmessage (), e);}    }

The creation of the handle object of the external resource is placed in parentheses after the Try keyword, and when the Try-catch code block executes, Java ensures that the Close method of the external resource is called. The code is not instantly concise many!

Try-with-resource is not a new feature of the JVM virtual machine, but the JDK implements a syntactic sugar, and when you decompile the above code, you will find that the JVM virtual machine still sees the previous wording:

 Public Static voidMain (string[] args) {Try{FileInputStream InputStream=NewFileInputStream (NewFile ("Test")); Throwable var2=NULL; Try{System.out.println (Inputstream.read ()); } Catch(Throwable var12) {var2=Var12; ThrowVar12; } finally {            if(InputStream! =NULL) {                if(Var2! =NULL) {                    Try{inputstream.close (); } Catch(Throwable var11) {var2.addsuppressed (VAR11); }                } Else{inputstream.close (); }            }        }    } Catch(IOException var14) {Throw Newruntimeexception (Var14.getmessage (), var14); }}

By deserializing the code, you may notice that there is a special handling of the exception in the code:

Var2.addsuppressed (VAR11);

This is another point of knowledge involved in the Try-with-resource syntax, called anomaly suppression. When an external resource is processed (such as read or write), if an exception is encountered and an exception is encountered during the subsequent shutdown of the external resource, you catch the exception that is encountered when processing the external resource, and the exception encountered when the resource is closed is "suppressed" but not discarded. By the exception of the Getsuppressed method, the suppressed anomaly can be extracted.

Summarize:

1, when the handle object of an external resource implements the Autocloseable interface, JDK7 can use Try-with-resource syntax to close the resource more gracefully and eliminate the plate code.

2, Try-with-resource, if the processing of external resources and external resources have encountered an exception, "Close exception" will be suppressed, "processing exception" will be thrown, but "close exception" is not lost, but is stored in the "processing exception" in the suppressed exception list.

Java Advanced Knowledge Point 3: Close resources more gracefully-try-with-resource syntax

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.