Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

raii - Any risk in a AutoCloseable wrapper for java.util.concurrent.locks.Lock?

With try-with-resource introduced in Java 7, I was surprised to see that that the Lock has not been retrofitted to be an AutoCloseable. It seemed fairly simple, so I have added it myself 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 an AutoCloseableReentrantReadWiteLock class and usage is as follows:

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

Since this seems so straightforward and canonical use of auto-closing RAII I am thinking there must be a good reason this should not be done. Anybody know?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Josh Bloch, the author of the proposal, said "This construct was designed for one thing and one thing only: resource management. It was not designed for locking."

There was a separate proposal to cover locks separately, but it didn't get anywhere.

I think the main reasons locks were not covered were:

  • not possible to add methods to an interface in Java 7
  • performance hit of creating an extra wrapper object that implemented the correct interface
  • philosophical objections to Lock being a different kind of resource from file handles (e.g. creation of a Lock does not entail invoking the lock method)

You can follow all the historical argy-bargy on the archive page, for example this thread.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...