在“此”上同步或Java中的私有对象? [英] Synchronization on "this" or private Object in Java?

查看:165
本文介绍了在“此”上同步或Java中的私有对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

避免在Java中同步(这个)?

有什么区别两段代码之间?每个的优点和缺点是什么?

What is the difference between the two pieces of code ? What are advantages and disadvantages of each?

1)

public class Example {
    private int value = 0;

    public int getNextValue() {
        synchronized (this) {
            return value++;
        }
    }
}

2)

public class Example {
    private final Object lock = new Object();
    private int value = 0;

    public int getNextValue() {
        synchronized (lock) {
            return value++;
        }
    }
}


推荐答案

我选择第二种方法的主要原因是我无法控制客户对我班级实例的处理。

The main reason why I would choose the 2nd approach is that I do not control what the clients do with the instances of my class.

如果,对某些人来说原因,有人决定使用我的类的实例作为锁,它们会干扰我班级内的同步逻辑:

If, for some reason, somebody decides to use an instance of my class as a lock, they will interfere with the synchronization logic within my class:

class ClientCode {
    Example exampleInstance;

    void someMethod() {
        synchronized (exampleInstance) {
            //...
        }
    }
}

如果在我的示例类中,我正在使用锁定没有其他人可以看到,他们不能干扰我的逻辑,并引入一个任意的互斥,如上述情况。

If, within my Example class, I'm using a lock that no one else can see, they cannot interfere with my logic and introduce an arbitrary mutex like in the above scenario.

总结一下,这只是一个应用程序信息隐藏原则。

To sum up, this is just an application of the information hiding principle.

这篇关于在“此”上同步或Java中的私有对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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