Please: try-with-resouces Lock support!

Stephen Colebourne scolebourne at joda.org
Sat Mar 5 11:08:36 PST 2011


On 4 March 2011 21:14, Bruce Chapman <brucechapman at paradise.net.nz> wrote:
> I wouldn't say the prime use case is locks. The prime use case is
> anywhere here you want to access the resource in a catch or finally,
> because the scope of the resource declaration is only the block.
>
> try(Resource r  = getResource()) {
>     doSomething(r);
> } catch (ResourceException e) {
>     System.out.println(e + " from " + r); // r undefined here
> }
>
> is invalid, you need to hoist the variable r outside the t-w-r so that
> it is in scope in the catch

Good point. And a concern to me.

> Resource r  = getResource();
> try(Resource rDash = r) {
>     doSomething(r);
> } catch (ResourceException e) {
>     System.out.println(e + " from " + r); // r visible
> }

Horrible.

> Resource r  = getResource();
> try(r) { // not currently permitted
>     doSomething(r);
> } catch (ResourceException e) {
>     System.out.println(e + " from " + r);
> }

Still not great.

But there is a "hack" solution:

try(Resource r  = getResource()) {try {
    doSomething(r);
} catch (ResourceException e) {
    System.out.println(e + " from " + r); // r undefined here
}}

Not ideal.

The problem is that the basic syntax for twr rather abuses try-catch.
In one way, it makes sense for r to be available within the catch and
finally blocks of twr. Its just that given the rest of Java, no-one
would expect that.

Right now, I don't see an easy syntax change to allow exceptions to
easily reference the resource. And that is a key downside IMO.

I do wonder if we're going to see coding standards down the line
suggesting that twr and try-catch-finally shouldn't be mixed.

Stephen



More information about the coin-dev mailing list