易失性变量是同步的吗? (java)
假设我有一个私有变量,并且有一个 setVariable()
方法,该方法是 synchronized
,这不是与使用 volatile
完全相同吗?代码>修饰符?
Say that I have a private variable and I have a setVariable()
method for it which is synchronized
, isn't it exactly the same as using volatile
modifier?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
不会。易失性意味着变量不会缓存在任何每线程缓存中,并且在需要时始终从主内存中检索其值。同步意味着这些每线程缓存将在某些点保持同步。理论上,如果许多线程需要读取变量的值,但很少更改该变量,则使用 volatile 变量可能会带来很大的速度损失。
No. Volatile means the variable isn't cached in any per-thread cache, and its value is always retrieved from main memory when needed. Synchronization means that those per-thread caches will be kept in sync at certain points. In theory, using a volatile variable can come with a great speed penalty if many threads need to read the value of the variable, but it is changed only rarely.
不,调用
synchronized
getXXX/setXXX 方法与读取/写入易失性
变量不同。多个线程可以同时读取或写入
易失性
变量。但一次只有一个线程可以读取或写入由同步块保护的变量。No, calling a
synchronized
getXXX/setXXX method is not the same as reading/writing to avolatile
variable.Multiple threads can concurrently read from or write to a
volatile
variable. But only one thread at a time can read from or write to a variable that is guarded by asynchronized
block.易失性
变量不是同步的(至少,不是以synchronized
东西同步的方式)。易失性的作用是确保每次使用变量时都会检索该变量(即:它阻止某些类型的优化),并确保以正确的顺序读取和写入该变量。可以想象,这可以模拟某些类型的同步,但如果您的设置器必须设置不止一件事,则它无法正常工作。 (例如,如果您设置两个易失性
变量,则存在一个点已设置而另一个未设置的点。)volatile
variables are not synchronized (at least, not in the waysynchronized
stuff is synchronized). Whatvolatile
does is ensure that a variable is retrieved each time it's used (ie: it prevents certain kinds of optimization), and IIRC that it's read and written in the correct order. This could conceivably emulate some kinds of synchronization, but it can't work the same if your setter has to set more than one thing. (If you set twovolatile
variables, for example, there will be a point where one is set and the other isn't.)其实没有。
易失性
实际上是同步的较弱形式,当字段被声明为易失性
时,编译器和运行时会理解该变量
是共享的并对其进行操作不应与其他内存操作一起重新排序。易失性变量不会缓存在寄存器或缓存中,对其他处理器来说是隐藏的,因此读取易失性
变量始终会返回任何线程最近的写入。Actually No.
volatile
is actually weaker form of synchronization, when field is declared as avolatile
the compiler and runtime understands that thisvariable
is shared and operations on it shouldn't be reordered with other memory operations. Volatile variable aren't cached in registers or in caches where they are hidden from other processors, so a read of avolatile
variable always return a recent write by any thread.只是一个例子:
将 stop 声明为易失性布尔值非常有用,这样第一个线程就可以拥有它的新值。
just an example :
it's useful to declare stopped as a volatile boolean for the first thread to have a fresh value of it.
没有任何关系。
基本上
There is no any relation.
Basically