简体   繁体   English

getter上的volatile和setter上的同步与两者上的同步相同吗?

[英]Is volatile on getter and synchronized on setter the same as synchronized on both?

In a concurrent program, is this safe: 在并发程序中,这是否安全:


private volatile int i;

public int getI() {
    return i;
}

public synchronized incrementI() {
    i++;
}

?

From what I know about synchronize , the changes are guaranteed to be available on i only for threads that acquires the lock monitor on the same object. 从我了解的synchronize ,所做的更改保证可上i只为获得相同对象的锁监视器线程。 So I think, the code above is not safe. 所以我认为,以上代码并不安全。 Please just confirm this if true, otherwise, please explain. 请确认是否正确,否则请解释。 Thanks. 谢谢。

This code is thread safe. 此代码是线程安全的。 Changes inside a synchronized method are passed on to all threads. 同步方法内部的更改将传递给所有线程。 And as you have made it volatile, all threads will not cache it, so will get latest copy. 并且,由于您将其变为易失性,因此所有线程都不会对其进行缓存,因此将获得最新副本。

Also this thread will be helpful Java volatile modifier and synchronized blocks 另外,该线程将对Java volatile修饰符和同步块有所帮助

Almost the exact example is given in "JMM Pragmatics" here . 这里的 “ JMM Pragmatics”几乎给出了确切的示例。

volatile provides the happens-before edges to make the changes before the setter visible to all things that happen after the getter, assuming the getter actually observed the set value. volatile提供了事件发生前的边缘,以使设置者之前发生的所有更改都可以在设置者之前看到,并假设设置者实际观察到了设置值。 synchronized in setter additionally gives the mutual exclusion, that volatile does not guarantee alone. 在setter中synchronized 还会互斥, volatile不能单独保证。

Since Integer i is the private instance variable of the class the synchronise instance method will work. 由于Integer i是该类的私有实例变量,因此同步实例方法将起作用。 You need to make sure all methods you add to class which modifies the i must synchronise using same object monitor. 您需要确保添加到类的所有方法(修改i的方法都必须使用相同的对象监视器进行同步)。

Please note i++ is not automic expression so only volatile will not work. 请注意,i ++不是自动表达式,因此仅volatile将不起作用。

You can use AtomicInteger for single value like this. 您可以使用AtomicInteger这样的单个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM