锁是否可自动关闭?

自动关闭是否可?也就是说,而不是:Locks

Lock someLock = new ReentrantLock();
someLock.lock();
try
{
    // ...
}
finally
{
    someLock.unlock();
}

...我可以说:

try (Lock someLock = new ReentrantLock())
{
    someLock.lock();
    // ...
}

...在Java 7中?


答案 1

我正在考虑自己做这件事,并做了这样的事情:

public class CloseableReentrantLock extends ReentrantLock implements AutoCloseable { 
   public CloseableReentrantLock open() { 
      this.lock();
      return this;
   }

   @Override
   public void close() {
      this.unlock();
   }
}

然后作为类的用法:

public class MyClass {
   private final CloseableReentrantLock lock = new CloseableReentrantLock();

   public void myMethod() {
      try(CloseableReentrantLock closeableLock = lock.open()) {
         // locked stuff
      }
   }
}

答案 2

否,Lock 接口(或 ReentrantLock 类)都不会实现该接口,而该接口是与新的 try-with-resource 语法一起使用所必需的。AutoCloseable

如果你想让它工作,你可以写一个简单的包装器:

public class LockWrapper implements AutoCloseable
{
    private final Lock _lock;
    public LockWrapper(Lock l) {
       this._lock = l;
    }

    public void lock() {
        this._lock.lock();
    }

    public void close() {
        this._lock.unlock();
    }
}

现在你可以像这样编写代码:

try (LockWrapper someLock = new LockWrapper(new ReentrantLock()))
{
    someLock.lock();
    // ...
}

不过,我认为你最好坚持使用旧的语法。更安全的是,锁定逻辑完全可见。


推荐