Any risk in the AutoCloseable wrapper for java.util.concurrent.locks.Lock?

With the try-with-resource introduced in Java 7, I was surprised to see that Lock not modified as AutoCloseable . It seemed pretty simple, so I added it as follows:

 class Lock implements AutoCloseable { private final java.util.concurrent.locks.Lock _lock; Lock(java.util.concurrent.locks.Lock lock) { _lock = lock; _lock.lock(); } @Override public void close() { _lock.unlock(); } } 

This works with the AutoCloseableReentrantReadWiteLock class, and usage is as follows:

 try (AutoCloseableReentrantReadWiteLock.Lock l = _lock.writeLock()) { // do something } 

Since it seems such a simple and canonical use of automatic closing of RAII, I think that there should be a good reason why this should not be done. Somebody knows?

+13
java raii try-with-resources
May 15, '13 at 20:26
source share
1 answer

This was a big discussion when try-with-resources was proposed in February / March 2009.

Josh Bloch, the author of the proposal, said: " This design was designed for only one thing: resource management only. It is not intended to be locked. "

There was a separate proposal to close the locks separately, but nothing came of it.

I think the main reasons for the locks were not covered:

  • unable to add methods to an interface in Java 7
  • performance when creating an additional wrapper object that implements the correct interface
  • philosophical objections to Lock are another type of resource from file descriptors (for example, creating a Lock not related to calling the Lock method)

You can follow the historical arga-barg on the archive page , for example this stream .

+18
Jun 11 '13 at 11:49 on
source share



All Articles