有一个专用的锁对象有用吗? [英] Is it useful to have a dedicated object for a lock?

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

问题描述

我正在清理遗留的 Java 代码,我发现了以下结构:

I am cleaning up a legacy java code and I found following construct:

final class QuiteComplexClass {
    private Object lock = new Object();

    void aMethod() {
        ...
        synchronized(lock) {
              ....
        }
    }
}

这里需要加锁的特殊对象吗?当我使用简单的 synchronized (this) 时有什么不同?

Is the special object for locking necessary here? What is difference when I used simple synchronized (this)?

我认为当类是公开可见的并且有人可能错误地在类实例上调用 synchronized 时,它可能很有用.但是这个类是包私有的,所以没有外部代码可以做到这一点.

I think it might by useful when the class is publicly visible and somebody may call synchronized on the class instance by mistake. But this class is package private so no external code can do that.

推荐答案

这里需要加锁的特殊对象吗?当我使用简单的 synchronized (this) 时有什么不同?

简短回答:不,没有必要,但除了添加 final 之外,我认为删除它几乎没有任何好处.

Short answer: no, it's not necessary but aside from adding final I see little to no benefit to remove it.

我倾向于使用锁定对象,因为与锁定this 相比,它们为我提供了更细粒度的锁定.例如,如果您要保护多个集合免受竞争条件的影响,您的类中可能有几个不同的锁对象.可以确定的一件事是,您应该始终确保将锁定字段设为 final.

I tend to like to use locking objects because they give me a more fine grained lock as opposed to locking on this. You might have a couple different lock objects in your class if you are, for example, protecting multiple collections from race conditions. One thing to sure is that you should always make sure to make the lock field final.

private final Object lock = new Object();

这就是说,如果一个类很简单,并且你想确保人们知道哪些方法是同步的,那么在方法上使用关键字也是非常合适的.正如您所提到的,这是一个内部类,但即便如此,处理外部类的开发人员可能想了解同步点.

This said, if a class is simple and you want to make sure people know which methods are synchronized then using the keyword on the methods is very appropriate as well. As you mentioned, this is an internal class but even then, developers working on the outer class might want to know about the sync points.

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

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