RFE: annotation for resource wrapper methods

Remi Forax forax at univ-mlv.fr
Sat Aug 10 17:00:19 UTC 2019


Hi Rob,
the problem is that if wrap() raises an exception before the wrapper is created and returned, the resource will be never closed.

The correct way to fix the issue is to use several assignments in the try-with-resources
 try (FileInputStream fileInputStream = new FileInputStream("filename");
      InputStream decoded = Base64.getDecoder().wrap(fileInputStream)) {
   ...
 }

regards,
Rémi

----- Mail original -----
> De: "Rob Spoor" <openjdk at icemanx.nl>
> À: "core-libs-dev" <core-libs-dev at openjdk.java.net>
> Envoyé: Samedi 10 Août 2019 18:00:16
> Objet: RFE: annotation for resource wrapper methods

> Hi,
> 
> When you wrap a resource (InputStream, etc) using a class constructor
> (e.g. new BufferedInputStream(...)), compilers usually don't complain.
> If you do the exact same thing using a utility method, compilers aren't
> that smart anymore. For instance, the following produces a warning that
> the FileInputStream may not be closed, even though the wrap method
> returns a new InputStream that closes the FileInputStream if it's closed
> itself:
> 
>     try (InputStream decoded = Base64.getDecoder().wrap(new
> FileInputStream("filename"))) {
>         ...
>     }
> 
> It would be nice if there were some annotation that we could use to mark
> a method as being resource-safe, because they either close the resource,
> or return a wrapper around it. It would be a bit like @SafeVarargs but
> for resources. Methods like wrap would then be annotated with this new
> annotation, and compilers shouldn't complain anymore. The alternative is
> a lot more verbose:
> 
>     try (@SuppressWarnings("resource") InputStream decoded =
> Base64.getDecoder().wrap(new FileInputStream(""))) {
>         ....
>     }
> 
> 
> (I don't know if this is the right mailing list, but I couldn't find a
> better one.)
> 
> 
> Kind regards,
> 
> Rob


More information about the core-libs-dev mailing list