Upcoming change in semantics to try-with-resources on a null resource
Joe Darcy
joe.darcy at oracle.com
Thu Feb 17 13:52:55 PST 2011
On 2/16/2011 3:06 PM, Joe Darcy wrote:
> Hello.
>
> After due consideration the JSR 334 expert group has decided the
> semantics of the try-with-resources statement on a null resource
> should be changed as follows: the compiler-generated calls to close a
> resource will only occur if the resource is non-null.
>
> Concretely, the semantics of the desugaring of the finally block are
> changed from
>
> finally {
> if (#primaryException != null) {
> try {
> #resource.close();
> } catch(Throwable #suppressedException) {
> #primaryException.addSuppressed(#suppressedException);
> }
> } else {
> #resource.close();
> }
> }
>
> to
>
> finally {
> if (#primaryException != null) {
> try {
> if(#resource != null)
> #resource.close();
> } catch(Throwable #suppressedException) {
> #primaryException.addSuppressed(#suppressedException);
> }
> } else {
> if(#resource != null)
> #resource.close();
> }
> }
>
FYI, inspired by a comment left on my blog [1], javac will hoist the
null check of the resource, resulting in the semantically equivalent but
shorter code
finally {
if (#resource != null)
if (#primaryException != null) {
try {
// if(#resource != null)
#resource.close();
} catch(Throwable #suppressedException) {
#primaryException.addSuppressed(#suppressedException);
}
} else {
// if(#resource != null)
#resource.close();
}
}
}
-Joe
[1]
http://blogs.sun.com/darcy/entry/project_coin_null_try_with#comment-1297968215000
More information about the coin-dev
mailing list