吸气剂和二传手应该同步吗? [英] Should getters and setters be synchronized?

查看:96
本文介绍了吸气剂和二传手应该同步吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private double value;

public synchronized void setValue(double value) {
    this.value = value;
}
public double getValue() {
    return this.value;
}

在上面的例子中,是否有任何一点让getter同步?

In the above example is there any point in making the getter synchronized?

推荐答案

我认为最好引用 Java Concurrency in Practice here:

I think its best to cite Java Concurrency in Practice here:


假设只有在写入共享变量时才需要使用同步,这是一个常见的错误。这根本不是真的。

It is a common mistake to assume that synchronization needs to be used only when writing to shared variables; this is simply not true.

对于每个可以由多个
线程访问的可变状态变量,所有访问到该变量必须使用相同的
锁执行。在这种情况下,我们说变量由
锁保护。

For each mutable state variable that may be accessed by more than one thread, all accesses to that variable must be performed with the same lock held. In this case, we say that the variable is guarded by that lock.

在没有同步的情况下,编译器,处理器和运行时可以做一些对操作似乎执行的顺序非常奇怪的事情。尝试推断在不完全同步的多线程程序中必须发生内存操作的顺序几乎肯定是不正确的。

In the absence of synchronization, the compiler, processor, and runtime can do some downright weird things to the order in which operations appear to execute. Attempts to reason about the order in which memory actions "must" happen in insufflciently synchronized multithreaded programs will almost certainly be incorrect.

通常情况下,你不必非常小心原语,所以如果这是一个 int 或一个 boolean 它可能是这样的:

Normally, you don't have to be so careful with primitives, so if this would be an int or a boolean it might be that:


当一个线程在没有同步的情况下读取变量时,它可能会看到一个
的陈旧值,但至少它看到了一个线程而不是一些随机值实际上放在
的值。

When a thread reads a variable without synchronization, it may see a stale value, but at least it sees a value that was actually placed there by some thread rather than some random value.

然而,这不是真的对于64位操作,例如在 long double 上,如果它们未被声明 volatile

This, however, is not true for 64-bit operations, for instance on long or double if they are not declared volatile:


Java内存模型要求fetch和
存储操作是原子的,但对于非易失性long和double
变量,允许JVM处理64位读或写两个
分开的32位操作。如果读取和写入发生在不同的
线程中,则可以读取非易失性long并将
返回到一个值的高32位和另一个值的低32位。

The Java Memory Model requires fetch and store operations to be atomic, but for nonvolatile long and double variables, the JVM is permitted to treat a 64-bit read or write as two separate 32-bit operations. If the reads and writes occur in different threads, it is therefore possible to read a nonvolatile long and get back the high 32 bits of one value and the low 32 bits of another.

因此,即使您不关心陈旧值,在多线程程序
中使用
共享可变长和双变量也是不安全的,除非它们被声明挥动或被锁守。

Thus, even if you don't care about stale values, it is not safe to use shared mutable long and double variables in multithreaded programs unless they are declared volatile or guarded by a lock.

这篇关于吸气剂和二传手应该同步吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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