java7 try-with-resources 很香

Java 7 brings some very nice features for Java developers lazy. Attempt resources is one of this feature, it can reduce the lines of code, make the code more robust. In this tutorial, I will discuss the contents of this feature.

1. The old method of clearing resources (before Java 7)

** We've been doing this a long time. For example, read the file from the file system. Code may look different, but the processes illustrated below:

public class ResourceManagementBeforeJava7 
{
    public static void main(String[] args) 
    {
        BufferedReader br = null;
        try
        {
            String sCurrentLine;
            br = new BufferedReader(new FileReader("C:/temp/test.txt"));
            while ((sCurrentLine = br.readLine()) != null) 
            {
                System.out.println(sCurrentLine);
            }
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                if (br != null)
                    br.close();
            } 
            catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

These types of code is very common in the application code library has a large number of IO operations.
It is important the nature of the code and try catch block, and having a specific logic in the application. But finally he blocked it? In most cases, finall block is simply copy and paste , the aim is to avoid damage by closing the resource thereof.
When you have 3-4 such resources to be shut down in a single finally block, the final block look more ugly . As we know, do not you think that these final block unnecessarily exist, we must close the resource in any way without any exceptions?
Java 7 solves this problem by try-with-resources function.

2. The method of using the new try-with-resources (Syntax example)

Now look at new ways to open and close resources in Java 7.

public class ResourceManagementInJava7 
{
    public static void main(String[] args) 
    {
        try (BufferedReader br = new BufferedReader(new FileReader("C:/temp/test.txt")))
        {
            String sCurrentLine;
            while ((sCurrentLine = br.readLine()) != null) 
            {
                System.out.println(sCurrentLine);
            }
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
}

Two things need to pay close attention:

  1. File resource (the BufferedReader) open in a special manner (in the small brackets) in the try block.
  2. finally block completely disappeared.

Last but not least is that the code looks very nice and easy to read. Well, right? But it actually work?

3. Actual How does it work?

In Java 7, we have a new super interfaces java.lang.AutoCloseable **. The interface has a method:

void close() throws Exception;

This interface Java documentation suggests any resources that must be closed when no longer needed on realization .
When we open any such AutoCloseable resources in a special try-with-resource block, after the completion of the try block, the JVM will "try ()" initialize all resource blocks in an immediate call to close () method .
For example, BufferedReader realized close () method following documents:

public void close() throws IOException {
    synchronized (lock) {
        if (in == null)
            return;
        in.close();
        in = null;
        cb = null;
    }
}

Due to the above method definition, when the JVM calls this method, all the basic flow of resources or IO will be closed.

4. add functionality to a custom resource

Well, this is a great resource to clean up the design. But it only applies to the native JDK class do? No. You can also use it for custom resources.
For example, I created a custom resource in the following code:

public class CustomResource implements AutoCloseable 
{
    public void accessResource() {
        System.out.println("Accessing the resource");
    }
     
    @Override
    public void close() throws Exception {
        System.out.println("CustomResource closed automatically");
    }
}

Now, I'll use it in the sample code:

public class TryWithCustomResource 
{
    public static void main(String[] args)
    {
        try(CustomResource cr = new CustomResource())
        {
            cr.accessResource();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
 
Putput in console:
 
Accessing the resource
CustomResource closed automatically

Output console clearly demonstrate that, after completion of the try block, the resource will automatically shut down.

5. Summary

This is carried out in Java 7 using automatic resource management the entire contents of try-with-resources. Let us point by point note the key elements:

  • Before Java 7, we must use the finally block to clean up resources. Finally, the block is not mandatory, but clean-up resources in order to prevent system damage.
  • Use Java 7, without explicitly resource cleanup. It is done automatically.
  • ({...} try (...)) to complete the automatic cleanup of resources in the resource initialization try-with-resources blocks.
  • Since the new interface AutoCloseable happen, so clean-up took place. After completion of the try block, JVM calls its immediately close method.
  • If you want to use this feature in a custom resource, you must implement AutoCloseable interface. Otherwise the program will not compile.
  • You should not call close () method in the code. JVM should automatically be called. Manually invoke it could lead to unexpected results.

Happy learning!

Guess you like

Origin www.cnblogs.com/qingmiaokeji/p/12555370.html