Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force try-with-resources Java 7

I have a class which implements AutoCloseable, and is intended to be used with Java 7's new try-with-resources construct. However, I can't figure out a way to guarantee that the user of my class uses try-with-resources. If this doesn't happen, then my class won't be able to close itself, and bad things will happen. Is there any way - language construct or otherwise - to enforce this? Even being able to detect whether or not I'm in a try-with-resources block so that I can throw an exception if not would be good (although a compile-time construct would be preferable).

Thanks!

like image 582
joshlf Avatar asked Jul 02 '13 16:07

joshlf


People also ask

How does Java 7 handle closing of resources?

Support for try-with-resources — introduced in Java 7 — allows us to declare resources to be used in a try block with the assurance that the resources will be closed after the execution of that block. The resources declared need to implement the AutoCloseable interface.

Can we use finally with try with resources?

Note: A try -with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try -with-resources statement, any catch or finally block is run after the resources declared have been closed.

Does Java 8 support try resources?

It is possible to create a utility method that reliably closes streams with a try-with-resource-statement. It is a bit like a try-finally that is an expression (something that is the case in e.g. Scala). With this method the example from the question looks like this: Set<Integer> photos = new HashSet<Integer>(Arrays.

Does try with resources automatically close?

The Java try with resources construct, AKA Java try-with-resources, is an exception handling mechanism that can automatically close resources like a Java InputStream or a JDBC Connection when you are done with them. To do so, you must open and use the resource within a Java try-with-resources block.


1 Answers

Unfortunately there's no way to protect yourself from user stupidity.

You can implement the finalize method to call close; this way you can be sure that the resource is closed at least when the object is garbage collected, even though you can't know when (or if) that happens.

If you can put restrictions on how your project is used, you may be able to enforce some policies using aspect oriented programming, but then you're not really using Java anymore.

like image 116
Joni Avatar answered Oct 20 '22 01:10

Joni