如果我在将由多个线程操作的对象中有多个可变属性,我理解它们应该同步。
class Doggie {
private String name;
private int age;
public void setName(String name) { this.name = name; }
public String getName() { return this.name; }
public void setAge(int age) { this.age = age; }
public int getAge() { return this.age; }
}
问题:
- Java 中的
return
和赋值不是原子操作吗? - 由于属性不一定相互关联,因此使用同一把锁同步并不总是有意义。如何组织锁定结构?
- 使用内在锁还是私有(private)对象锁模式更好?
最佳答案
- Are not return and assignment atomic operations in Java?
是的,它们是原子的(至少在某些情况下),但原子性不是唯一的问题。另一个重要问题是,一个线程对属性的写入操作是否保证对另一个线程对同一属性的后续读取可见。
当读和写在同一个线程中时,读保证看到先写。
当读取和写入在不同的线程中时,只有在两个线程正确同步时才能保证读取看到较早的写入......或者如果属性声明为
volatile
.
请注意,原始锁/互斥锁并不是唯一的同步方式。
- Since properties might not necessarily be interrelated, it does not always make sense to synchronize with the same lock. How to organize the locking structure?
如果(且仅当)可能发生锁争用时,使用多个锁才有意义。在您的示例中,只有当某些 Doggie
实例接收到非常高的获取和/或设置操作率时,锁争用才可能成为问题。
- Is it better to go with the intrinsic lock or a private Object lock pattern?
这取决于。如果您的应用程序要使用 Doggie
对象的原始锁,那么您可能会发生锁争用,甚至可能会意外锁定 get 和 set 操作。在这种情况下,私有(private)锁可能是可取的。否则,私有(private)锁是不必要的开销。
关于 java 。如何正确同步 getter 和 setter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3076014/