Search This Blog

Java: try with AutoCloseable resources

1. Multiple AutoCloseable resources

  try (InputStream in = getInputStream(); OutputStream out = getOutputStream()) {
      ... ...
  }
  
The resources are closed in the reverse order of declaration.


2. Resource leaking caused by nested constructors

There is possible resource leaking issue for the code below:
  try(InputStream in = new MyFilterInputStream(new BufferedInputStream(new FileInputStream("/tmp/test.file")))) {
      ... ...
  }
  
Because any checked exception from the chain of the constructors can cause resource failing to close. The code below with multiple declared AutoCloseables should be used:
  try(FileInputStream fis = new FileInputStream("/tmp/test.file");
      BufferedInputStream bis = new BufferedInputStream(fis);
      MyFilterInputStream mfis = new MyFilterInputStream(bis)) {
      ... ...
  }
  



3. What will happen if the AutoCloseable is null

A resource is closed only if it initialized to a non-null value. So the code works without having to worry about NPE when in is null.
  try(InputStream in = createNew==true? createInputStream(): null) {
      if(in==null) {
          ... ...
      }
  }
  




see also

No comments:

Post a Comment