commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Damjan Jovanovic <dam...@apache.org>
Subject Backporting try-with-resources to Java < 7 (was: Re: [imaging] Closing stream)
Date Sun, 03 Nov 2013 08:30:04 GMT
On Fri, Oct 25, 2013 at 1:52 PM, Matt Benson <gudnabrsam@gmail.com> wrote:

> On Oct 25, 2013 6:30 AM, "Damjan Jovanovic" <damjan.jov@gmail.com> wrote:
> >
> > On Fri, Oct 25, 2013 at 12:36 PM, Jörg Schaible
> > <Joerg.Schaible@scalaris.com> wrote:
> > > Hi Damjan,
> > >
> > > Damjan Jovanovic wrote:
> > >
> > > [snip]
> > >
> > > Thanks for explanation.
> > >
> > >> We would be able to adapt that for Java < 1.7 by swallowing the close
> > >> exception instead of calling addSuppressed() on the primary exception,
> > >> but the show stopper is catching and rethrowing the primary exception
> > >> (Throwable), which javac < 1.7 refuses to compile because it doesn't
> > >> do "Rethrowing Exceptions with More Inclusive Type Checking"
> > >> (
>
> http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
> ).
> > >>
> > >> But this would work and always sets succeeded correctly without
> > >> catch/re-throw:
> > >>
> > >> final InputStream is = factoryMethodThatCanThrow();
> > >> boolean succeeded = false;
> > >> try {
> > >>     try {
> > >>         is.methodThatCanThrow();
> > >>     } finally {
> > >>     }
> > >>     succeeded = true;
> > >> } finally {
> > >>     closeSafely(!succeeded, is);
> > >> }
> > >
> > > I guess the nested try was unintentionally ;-)
> > >
> > > Cheers,
> > > Jörg
> >
> > Well that actually won't work, because the "succeeded = true;" will be
> > skipped if there is a "return;" in the inner try.
> >
> > Other than a custom Java compiler, I guess there's no clean way of
> > doing this in Java < 1.7. There's really only option 2 - with being
> > careful to always set succeeded correctly on all paths out of the try
> > block. Almost like releasing memory in C.
> >
>
> I haven't deeply followed this conversation, but would this be a candidate
> for a [weaver] module?
>
> Matt
>
>

[weaver] I am less sure about, but by playing with Objectweb's ASM I did
manage to compile code with try-with-resources on Java 7, change the class
file version, do some bytecode manipulation to delete calls to
Throwable.addSuppressed(), and get it to work on Java < 7.

Made it into a Maven plugin and it works well :). Also verified other Java
7 language features (binary literals, underscores in numeric literals,
strings in switch, diamonds, exception multi-catch and re-throw) work on
Java < 7 because they're just syntactic sugar.

It's very small and simple - 143 lines in 1 file. Is it worth adding as a
new commons project? Or do we not host (projects that contain) Maven
plugins?

Damjan

Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message