How to terminate resources in try-with-resources (original) (raw)
Joe Darcy joe.darcy at oracle.com
Mon Jan 31 19:15:36 PST 2011
- Previous message: try-with-resources and null resource
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Hello.
In addition to mulling over nulling in the try-with-resources statement, the JSR 334 expert group has decided to slightly amend the syntax of try-with-resources statement: an optional trailing semicolon will now be allowed to terminate the list of resources.
Previously, a semicolon could only be used as a separator between two resources as in
try(Resource r0 = new Resource(); Resource r1 = new Resource();
Resource r2 = new Resource()) {...}
or reformatted as
try(Resource r0 = new Resource();
Resource r1 = new Resource();
Resource r2 = new Resource()) {...}
However, including an extraneous semicolon at the end of the list would be rejected as a syntax error:
try(Resource r0 = new Resource();
Resource r1 = new Resource();
Resource r2 = new Resource();) {...} // Illegal under JSR 334 EDR!
While requiring a semicolon at the end of a list of resources would be excessive, especially when there is only a single resource being managed, optionally allowing a terminating resource offers several advantages. First, when adding a resource to the list of resources being managed, there are fewer necessary edits when cutting and pasting. More importantly, programmatic generation of code is simplified since the code generation logic does not need to know ahead of time whether or not a particular resource will be the last one when the declaration for that resource is generated. The simple rule "terminate a resource declaration with a semicolon" will result in acceptable code, even if the code is not ideal style-wise. Finally, allowing an optional trailing semicolon is consistent with the handling of commas in array initializers,
int[] values = {1,
2,
3, // Legal
};
and the handling of commas in the declaration of enum constants.
enum PrimaryColor {
RED,
GREEN,
BLUE, // Legal
;
}
The full amended grammar for try-with-resources which allows the optional trailing semicolon is:
TryStatement: try Block Catches try Block Catches_opt Finally try ResourceSpecification Block Catches_opt Finally_opt
ResourceSpecification: ( Resources ;_opt )
Resources: Resource Resource ; Resources
Resource: VariableModifiers_opt Type VariableDeclaratorId = Expression
The necessary compiler changes to implement the revised grammar have been pushed into a JDK 7 integration repository [1] and will appear in a promoted build in due course.
-Joe
[1] http://hg.openjdk.java.net/jdk7/tl/langtools/rev/2ab47c4cd618
- Previous message: try-with-resources and null resource
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]