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!
close
ing your class manually instead of automagically with a try-with-resources? Would creating afinalize
method that calledclose
fix your problem? – Hypermeterfinalize
is not guaranteed to be called. The GC may decide not to call it. – Tiedfinalize
is probably the reason that try-with-resources was introduced. – Tiedclose
on your class before it gets GCed. – Hypermeter