Proposal: Automatic Resource Management
Joshua Bloch
jjb at google.com
Tue Sep 1 19:39:25 PDT 2009
Sean,
Perhaps I am missing something, but wouldn't this change the semantics of
existing programs?
Josh
On Tue, Sep 1, 2009 at 7:32 PM, Sean R. Drucker <
sean.drucker at frameworkplus.com> wrote:
> My suggestion was assuming an implementation like (2). Here is a use case:
>
> interface SQLIterator<E> extends Iterator<E>, Disposable<SQLException> {
> }
>
> interface SQLTable extends Iterable<Row> {
> SQLIterator<Row> iterator();
> }
>
> Current usage pattern:
>
> public static void current(SQLTable table) throws SQLException {
> final SQLIterator<Row> itr = table.iterator();
> try {
> while (itr.hasNext()) {
> final Row row = itr.next();
> ...
> }
> } finally {
> itr.close();
> }
> }
>
> Equivalent using Automatic Resource Management:
>
> public static void arm(SQLTable table) throws SQLException {
> for (final Row row: table) {
> ...
> }
> }
>
> The specification added to Disposable would be something like:
>
> If an implementation of Iterable<E>.iterator() returns a static type that
> extends both Iterator<E> and Disposable<X> (which is possible due to
> covariance), then when an instance of that Iterable is used in a for-each
> loop, the Iterable.iterator() will always have its Disposable.close() method
> called after iteration is complete or terminated (either an early return or
> an iteration exception). Any checked exception X thrown from
> Disposable.close() will need to be caught or rethrown and will suppress any
> prior iteration exception.
>
> Suppressing exceptions seems reasonable as that is what is done in the
> current usage pattern. Also, as a practical matter, if a close() method was
> ever to throw an exception (which is highly rare), it would indicate a far
> greater problem (usually a lost resource connection) than any problem in the
> iteration.
>
> Thanks... Sean
>
> Neal Gafter wrote:
>
> On Tue, Sep 1, 2009 at 4:24 PM, Rémi Forax <forax at univ-mlv.fr <mailto:
>> forax at univ-mlv.fr>> wrote:
>>
>> This will require to introduce a new interface IterableDisposable or
>> something like that to ease the use of such pattern.
>>
>>
>> That's one way to do it. Here are two others:
>>
>> 1. Dynamically test the type of the iterator to see if it extends
>> Disposable.
>>
>> 2. Statically test the static return type of
>> iterableExpression.iterator(), which due to covariance may be a type that
>> extends both Iterable<?> and Disposable.
>>
>> I think (2) works best, so that the compiler can see the exceptions
>> statically thrown by iterableExpression.iterator().close() and the
>> programmer won't have to catch(Exception).
>>
>> Cheers,
>> Neal
>>
>>
More information about the coin-dev
mailing list