java.util.concurrent.locks.Lock的AutoCloseable包装中的任何风险? [英] Any risk in a AutoCloseable wrapper for java.util.concurrent.locks.Lock?
问题描述
使用 try-with-resource 在Java 7中引入了code>
,我惊讶地发现 锁定
尚未改装为 AutoCloseable
。它看起来相当简单,所以我自己添加如下:
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();
}
}
这适用于 AutoCloseableReentrantReadWiteLock
类和用法如下:
This works with an AutoCloseableReentrantReadWiteLock
class and usage is as follows:
try (AutoCloseableReentrantReadWiteLock.Lock l = _lock.writeLock()) {
// do something
}
因为这看起来很简单规范使用自动关闭 RAII 我认为必须有一个很好的理由不应该这样做。有人知道吗?
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?
推荐答案
当尝试使用资源$ c $时这是一个很大的争论c>于2009年2月/ 3月提出。
This was a big debate when try-with-resources
was proposed in February/March 2009.
该提案的作者Josh Bloch说:这个结构只针对一件事,一件事:资源管理。它不是为锁定而设计的。
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:
- 无法在Java 7中向接口添加方法
- 性能命中创建一个实现正确接口的额外包装器对象
- 哲学异议
Lock
是一种与文件句柄不同的资源(例如创建Lock
不需要调用lock
方法)
- 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 aLock
does not entail invoking thelock
method)
这篇关于java.util.concurrent.locks.Lock的AutoCloseable包装中的任何风险?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!