在函数中通过类名同步将在扩展类中有效吗? [英] is synchronized by class name in a function will be valid across extended classes?

查看:145
本文介绍了在函数中通过类名同步将在扩展类中有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在基类中有一个方法foo使用Synchronized(类名),以及两个扩展基类的类A和B.如果我从一个实例调用foo而两个不同线程中的B实例将被同步。这是一个示例代码:

I have a methode foo in base class uses Synchronized (class name) , and two classes A and B that extends the base class. if i called foo from A instance and B instance in two different thread are they gonna be Synchronized. here's a sample code :

class BaseClass { 
        void foo() {
        synchronized(BaseClass.class)   
            // do something like increment count 
        }   
    }


    class A extends BaseClass {
    }


    class B extends BaseClass {
    }

    A a = new A(); 
    B b = new B();
    //in thread 1
    a.foo() ; 
    //in thread 2
    b.foo() ;


推荐答案

是的,这将在所有内容中同步所有类的实例扩展 BaseClass (包括 BaseClass 本身)。 BaseClass.class 引用基本上是整个类加载器的单个引用。你真的想要吗?

Yes, that will be synchronized across all instances of all classes extending BaseClass (including BaseClass itself). The BaseClass.class reference will basically be a single reference for the whole classloader. Do you really want that?

通常,当需要同步时,静态方法应该在静态的东西上同步,而实例方法应该在某些东西上同步与实例有关。我个人不喜欢同步这个引用 - 因为这些引用都可以在其他地方找到,所以其他代码可以在同一个监视器上同步,这使得很难推断同步。相反,我倾向于:

Usually, when synchronization is required, static methods should synchronize on something static, and instance methods should synchronize on something related to the instance. Personally I don't like synchronizing on either this or a Class reference - as both of those references are available elsewhere, so other code could synchronize on the same monitor, making it hard to reason about the synchronization. Instead, I would tend to have:

public class Foo {
    private final Object instanceLock = new Object();

    public void doSomething() {
        synchronized (instanceLock) {
            // Stuff
        }
    }
}

public class Bar {
    private static final Object staticLock = new Object();

    public static void doSomething() {
        synchronized (staticLock) {
            // Stuff
        }
    }
}

(我通常只使用 lock 作为名称;我为了清楚起见,我们在这里做得更明确了。)

(I typically actually just use lock as the name; I've just made it more explicit here for clarity.)

这篇关于在函数中通过类名同步将在扩展类中有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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