Locks AutoCloseable? [英] Are Locks AutoCloseable?

查看:134
本文介绍了Locks AutoCloseable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Locks AutoCloseable?也就是说,而不是:

Are Locks AutoCloseable? That is, instead of:

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

我可以说:

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

Java 7中的

in Java 7?

推荐答案

不, 锁定 界面(也不是 ReentrantLock class)实现 AutoCloseable 接口,该接口与新的try-with-resource语法一起使用。

No, neither the Lock interface (nor the ReentrantLock class) implement the AutoCloseable interface, which is required for use with the new try-with-resource syntax.

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

If you wanted to get this to work, you could write a simple wrapper:

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();
    }
}

现在你可以编写如下代码:

Now you can write code like this:

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

我觉得你的生活会更好但是,坚持使用旧语法。让锁定逻辑完全可见更安全。

I think you're better off sticking with the old syntax, though. It's safer to have your locking logic fully visible.

这篇关于Locks AutoCloseable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆