Upcoming change in semantics to try-with-resources on a null resource

Rémi Forax forax at univ-mlv.fr
Thu Feb 17 14:10:36 PST 2011


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







More information about the coin-dev mailing list