Java 7-style resource blocks?


The Closeable objects have the use( () -> Unit) utility, it is working great as long as I only have a single Closeable object. When there are multiple such objects that I have to handle what is the best option? when e.g. only 2 objects, I can embed it like

openResource1().use {
  openResource2().use {
  //actually do something

but this may look a bit weird after about 3 closeable objects. Do you have plan to have something similar to java 7 resource blocks?

Thank you,

1 Like

We are not planning a dedicated language feature for this, btu maybe we can improve on our calling syntax to beautify this case a little. Not sure what'd be the best way though

1 Like

Inspiration comes from "defer" example It can be transformed to something like this:

  withCloseables {   val resource1 = use(TestCloseable(1))   val resource2 = use(TestCloseable(2))   // do something   }

Or with extension method available only within "withCloseables" block:

  withCloseables {   val resource1 = TestCloseable(1).autoClose()   val resource2 = TestCloseable(2).autoClose()   // do something   }

Full code:

Looks cool! Thanks

By current API convention "with" means placing its argument as "this" into the following block. Using with* to put something as "this" (which is required for "autoclose" or "use" to work) somewhat confuses. Do you have other names for establishing "resource context"? Overall, I like the idea.

I'm not sure if I like this. My concern is that I have to use both withCloseables and autoClose. It's too easy to forget the latter as it's rather hidden at the end of line.

I’d prefer the Lombok[1] way:

@Cleanup val resource1 = TestCloseable(1); @Cleanup val resource2 = TestCloseable(2);

All the annotated resources get closed in their reverse declaration order when they get out of scope (like destructors would do) and all exceptions get rethrown (IIRC with exception chaining and addSuppressed). It needs a compiler support (or hack as in case of Lombok), but this should be rather simple.

Actually, I’d like to propose a new feature maybe ensuring that no resource cleanup gets ever forgotten:
Require all Autocloseable resource creations to be annotated with either Cleanup or NoCleanup.