Java 7 new features: Try-with-resources (TWR)

Source: Internet
Author: User

Java 7 new features: Try-with-resources (TWR)
Java 7 new features Try-with-resources (TWR) This change is easy to explain, but it has proved to have hidden subtleties, which
Made it much less easy to implement than originally stored ed. The basic idea is to allow
A resource (for example, a file or something a bit like one) to be scoped to a block in
Such a way that the resource is automatically closed when control exits the block.
This is an important change, for the simple reason that has Ally no one gets manual resource closing 100 percent right. until recently, even the reference how-tosfrom Sun were wrong. the proposal submitted to Project Coin for this change
Provided des the astounding claim that two-thirds of the uses of close () in the JDK had
Bugs in them!
Fortunately, compilers can be made to produce exactly the sort of pedantic, boilerplate code that humans so often get wrong, and that's the approach taken by this change.
This is a big help in writing error-free code. To see just how helpful, consider how
You 'd write a block of code that reads from a stream coming from a URL (url) and
Writes to a file (out) with Java 6. Here's one possible solution.
How close did you get? The key point here is that when handling external resources,
Murphy's Law applies-anything can go wrong at any time:
■ The InputStream can fail to open from the URL, to read from it, or to close
Properly.
■ The File corresponding to the OutputStream can fail to open, to write to it, or
To close properly.
■ A problem can arise from some combination of more than one factor.
This last possibility is where a lot of the headaches come from-a combination
Exceptions is very difficult to deal with well.
This is the main reason for preferring the new syntax-it's much less error-prone.
The compiler isn't susceptible to the mistakes that every developer will make when trying to write this type of code manually.
Let's look at the Java 7 code for debugging the same task as listing 1.3. As before, url
Is a URL object that points at the entity you want to download, and file is a File object
Where you want to save what you're re downloading. Here's what this looks like in Java 7.

try (OutputStream out = new FileOutputStream(file);InputStream is = url.openStream() ) {byte[] buf = new byte[4096];int len;while ((len = is.read(buf)) > 0) {out.write(buf, 0, len);}}

This basic form shows the new syntax for a block with automatic management-
Try with the resource in round brackets. For C # programmers, this is probably a bit
Reminiscent of a using clause, and that's a good conceptual starting point when working with this new feature. the resources are used by the block, and they're automatically disposed of when you're done with them.
You still have to be careful with try-with-resources, as there are cases where
Resource might still not be closed.
For example, the following code wocould not close its
FileInputStream properly if there was an error creating the ObjectInputStream
From the file (someFile. bin ).

try ( ObjectInputStream in = new ObjectInputStream(newFileInputStream("someFile.bin")) ) {...}
Let's assume that the file (someFile. bin) exists, but it might not be an ObjectInput
File, so the file might not open correctly. Therefore, the ObjectInputStream wouldn't
Be constructed and the FileInputStream wouldn't be closed!
The correct way to ensure that try-with-resources always works for you is to split
Resources into separate variables.


try ( FileInputStream fin = new FileInputStream("someFile.bin");ObjectInputStream in = new ObjectInputStream(fin) ) {...}

One other aspect of TWR is the appearance of enhanced stack traces and suppressed
Exceptions. Prior to Java 7, exception information cocould be swallowed when handling
Resources
. This possibility also exists with TWR, so the stack traces have been enhanced
To allow you to see the type information of exceptions that wocould otherwise be lost.
For example, consider this snippet, in which a null InputStream is returned from
A method:
try(InputStream i = getNullStream()) {i.available();}

This will give rise to an enhanced stack trace, in which the suppressed NullPointerException (NPE for short) can be seen: Exception in thread "main" java. lang. NullPointerException
At wgjd. ch01.ScratchSuprExcep. run (ScratchSuprExcep. java: 23)
At wgjd. ch01.ScratchSuprExcep. main (ScratchSuprExcep. java: 39)
Suppressed: java. lang. NullPointerException
At wgjd. ch01.ScratchSuprExcep. run (ScratchSuprExcep. java: 24)
1 more


We encourage you to use try-with-resources as soon as you're able, to eliminate unnecessary bugs from your codebase.
TWR and AutoCloseable
Under the hood, the TWR feature is achieved by the introduction of a new interface,
Called AutoCloseable, which a class must implement in order to be able to appear
As a resource in the new TWR try clause. Because of the Java 7 platform classes have
Been converted to implement AutoCloseable (and it has been made a superinterface of Closeable), but you shoshould be aware that not every aspect of the platform
Has yet adopted this new technology. It's supported as part of JDBC 4.1, though.
For your own code, you shocould definitely use TWR whenever you need to work
Resources. It will help you avoid bugs in your exception handling. Reading Notes: The Well-Grounded Java Develope
 

Related Article

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.