The second part of the java9 series - syntax enhancement of automatic resource closing

I plan to write a series of articles about java 9 in the next period of time. Although java 9 is not a core java version like Java 8 or Java 11, there are still many features worth paying attention to. Looking forward to your following me, I will write a series of articles about java 9, about ten articles.

In the Java 9 release, the try-with-resources syntax supported since JDK 7 has been improved. Although it's only a small improvement, I still hope to introduce him to you, let's improve a little bit every day together.

1. Let’s talk about try-with-resources of Java7 (the improved version of Java9 is later)

Before Java 7, there was no try-with-resources syntax, and all stream destruction actions had to be closed manually by writing code in the finally method. Write a string to a file as in the code below.

@Test
void testStream() throws IOException {
  String fileName = "D:\\data\\test\\testStream.txt";

  FileOutputStream fos = new FileOutputStream(fileName);  //Create IO pipeline stream
  OutputStreamWriter osw = new OutputStreamWriter(fos);
  BufferedWriter bw = new BufferedWriter(osw);

  try{
    bw.write("handwritten code Stream closing of the stream");
    bw.flush();
  }finally{
    bw.close();   //Manually close the IO pipe stream
    osw.close();
    fos.close();
  }
}

Since the Java 7 version, the try-with-resources syntax is provided. We only need to include the pipeline flow with try(). After the execution of the try code segment, the IO pipeline flow will be automatically closed, and we do not need to write code to close it. , which is neat!

@Test
void testTry() throws IOException {
  String fileName = "D:\\data\\test\\testTry.txt";
  try(FileOutputStream fos = new FileOutputStream(fileName);
      OutputStreamWriter osw = new OutputStreamWriter(fos);
      BufferedWriter bw = new BufferedWriter(osw);){
    bw.write("IO Piped streams are automatically invoked close()method");
    bw.flush();
  }
}

2. Avoid mistakes

Many small partners are prone to fall into misunderstandings after knowing the try-with-resources syntax

  • Myth 1: Only IO pipeline streams can use the try-with-resources syntax for automatic resource closure
  • Misunderstanding 2: All class objects with the close() method will automatically call the close() method to close resources

Misunderstanding 1 narrows the scope of practice, while Misunderstanding 2 exaggerates the scope of practice. So what kind of resources can be automatically closed? The answer is that classes that implement the AutoCloseable or Closeable interface can automatically close resources.

public interface Closeable extends AutoCloseable {
    public void close() throws IOException;
}

The Closeable interface inherits from the AutoCloseable interface, both of which contain a close() method. If your custom class that occupies system resources needs to be reclaimed, please implement one of these two interfaces, and perform resource reclamation and closing in the close() method. In this way, your custom classes can also use the try-with-resources syntax to recycle and close resources.

3. Improvement of try-with-resources in Java 9

The try-with-resources syntax has been improved in java 9. The try() of the try-with-resources syntax can contain variables, and multiple variables are separated by semicolons.
The purpose of such improvements is to make the semantics clearer and to separate the resource creation code from the syntax that attempts resource recycling.

  • Semantic 1: try to execute the code segment, if an exception is thrown, handle the exception
  • Semantic 2: Try to close resources automatically, who? Close the variable contained by try()
@Test
void testJava9Try() throws IOException {
  String fileName = "D:\\data\\test\\testJava9Try.txt";

  FileOutputStream fos = new FileOutputStream(fileName);
  OutputStreamWriter osw = new OutputStreamWriter(fos);
  BufferedWriter bw = new BufferedWriter(osw);

  try(bw;osw;fos){  //Note here: try to recycle the resources corresponding to these three objects, compare with the java 7 code above
    bw.write("Java9-can be called automatically close()method");
    bw.flush();
  }
}

Welcome to pay attention to my blog, there are many fine collections in it

This article is reproduced to indicate the source (must be linked, not just text): Antetokounmpo Blog - zimug.com

If you find it helpful, please like and share! Your support is my inexhaustible creative motivation! . In addition, the author recently output the following fine content, looking forward to your attention.

Tags: Spring

Posted by newman on Wed, 11 May 2022 12:45:25 +0300