爪哇.如何正确同步 getter 和 setter? [英] Java. How to properly synchronize getters and setters?

查看:34
本文介绍了爪哇.如何正确同步 getter 和 setter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在一个对象中有多个可变属性,并且由多个线程对其进行操作,我理解它们应该是同步的.

If I have several mutable properties in an object that will be acted upon by several threads, I understand they should be synchronized.

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; }

}

问题:

  • return 和赋值在 Java 中不是原子操作吗?
  • 由于属性可能不一定是相互关联的,因此与同一个锁同步并不总是有意义的.如何组织锁定结构?
  • 使用内在锁还是私有对象锁模式更好?
  • Are not return and assignment atomic operations in Java?
  • 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?
  • Is it better to go with the intrinsic lock or a private Object lock pattern?

推荐答案

  • Java 中的返回和赋值不是原子操作吗?

是的,它们是原子的(至少在某些情况下),但原子性并不是唯一的问题.另一个重要问题是,一个线程对属性的写入操作是否保证对不同线程对同一属性进行的后续读取可见.

Yes they are atomic (in some cases at least), but atomicity is not the only issue. Another important issue is whether the action of a write to an attribute by one thread is guaranteed to be visible to a following read for the same attribute made by a different thread.

  • 当读和写在同一个线程中时,保证读看到更早的写.

  • When the reads and writes are in the same thread, the read is guaranteed to see the earlier write.

当读取和写入在不同的线程中时,如果两个线程同步正确……或者如果属性被声明为volatile,则读取只能保证看到较早的写入.

When the reads and writes are in different threads, the read is only guaranteed to see the earlier write if the two threads synchronize properly ... or if the attribute is declared as volatile.

请注意,原始锁/互斥锁不是同步的唯一方法.

Note that primitive locks/mutexes are not the only way to synchronize.

  • 由于属性可能不一定是相互关联的,因此与同一个锁同步并不总是有意义的.如何组织锁定结构?

当(且仅当)可能发生锁争用时,使用多个锁才有意义.在您的示例中,只有当某些 Doggie 实例接收到非常高的 get 和/或 set 操作率时,锁争用才可能是一个问题.

It makes sense to use multiple locks if (and only if) lock contention is likely. In your example, lock contention is only likely to be an issue if some Doggie instance receives a very high rate of get and/or set operations.

  • 使用内在锁还是私有对象锁模式更好?

这取决于.如果您的应用程序将使用 Doggie 对象的原始锁,那么您可能会遇到锁争用,甚至意外锁定 get 和 set 操作.在这种情况下,私人锁可能是可取的.否则,私有锁是不必要的开销.

It depends. If your application is going use the Doggie object's primitive lock, then you might get lock contention or even unintended locking out of get and set operations. In that case a private lock might be advisable. Otherwise, a private lock is an unnecessary overhead.

这篇关于爪哇.如何正确同步 getter 和 setter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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