Please: try-with-resouces Lock support!

David Holmes David.Holmes at oracle.com
Wed Feb 23 16:42:17 PST 2011


I suspect Joe will shut this down as being out of scope for coin-dev in 
its present state, but my 2c

Gernot Neppert said the following on 02/24/11 03:31:
> this has been discussed here before, but somehow got lost:
> Wouldn't it be very handy having a class 
> "java.util.concurrent.AutoLockable" that could be used as follows:

No not really. The way try-with-resources has evolved really doesn't 
mesh with lock usage. As Neal already mentioned the overhead of creating 
the AutoLockable per lock operation is simply prohibitive. Even if you 
retrofitted Lock with AutoCloseable you would still need (given t-w-r 
synatx) to have a helper method to acquire the lock and return it so you 
can assign it to the local:

  try ( Lock l = Lock.lockAndReturn(lock) ) {
   ...
  }

This is just a round-hole vs square-peg situation, and trying to make it 
fit really doesn't add anything to clarity or useability in my view.

I can imagine a more general (more specific?) t-w-r that might allow:

try (lock) {
    ...
}

but that would be for future debate.

Cheers,
David Holmes

> try(AutoLockable locked = AutoLockable.locked(lock))
> {
> // Do something in locked scope
> }
> 
> It would look something like this:
> 
> package java.util.concurrent.locks;
> 
> public abstract class AutoLockable implements AutoCloseable {
> 
>      public static AutoLockable locked(final Lock lock)
>      {
>          lock.lock();
>          return new AutoLockable() {
> 
>              @Override
>              public void close() {
>                  lock.unlock();
>              }
>          };
>      }
> 
>      public abstract void close();
> }
> 
> 



More information about the coin-dev mailing list