Upcoming change in semantics to try-with-resources on a null resource
Joe Darcy
joe.darcy at oracle.com
Thu Feb 17 16:50:21 PST 2011
Rémi Forax wrote:
> On 02/17/2011 10:52 PM, Joe Darcy wrote:
>
>> 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
>>
>
> There is another cheap optimization.
> Only generate the nullcheck if the resource is not initialized with a
> new XXX.
> try(XXX resource = new XXX()) {
> ...
> }
>
> Allocating the resource in the try expression is really a common code.
>
> Rémi
>
>
Hi Rémi.
Thanks for the suggestion; I've recored it in 7020499 "Project Coin:
improvements to try-with-resources desugaring."
I don't plan to use that optimization in the initial push of the new
semantics, but we'll certainly consider it for future refinements.
Thanks,
-Joe
More information about the coin-dev
mailing list