为什么Java中的变量不是默认的volatile? [英] Why aren't variables in Java volatile by default?

查看:98
本文介绍了为什么Java中的变量不是默认的volatile?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能类似的问题:

你曾经在Java中使用volatile关键字吗?




今天我在调试我的游戏;它有一个非常困难的线程问题,每隔几分钟就会显示出来,但很难重现。首先,我在每个方法中添加了 synchronized 关键字。那没用。然后我将 volatile 关键字添加到每个字段。问题似乎只是解决了问题。

Do you ever use the volatile keyword in Java?


Today I was debugging my game; It had a very difficult threading problem that would show up every few minutes, but was difficult to reproduce. So first I added the synchronized keyword to each of my methods. That didn't work. Then I added the volatile keyword to every field. The problem seemed to just fix itself.

经过一些实验,我发现负责的字段是 GameState 对象跟踪我的游戏当前状态,可以是游戏也可以是忙碌。忙时,游戏会忽略用户输入。我所拥有的是一个不断更改 state 变量的线程,而Event线程则读取 state 变量。但是,在一个线程更改变量后,另一个线程需要几秒钟来识别更改,这最终会导致问题。

After some experimentation I found that the field responsible was a GameState object which kept track of my game's current state, which can be either playing or busy. When busy, the game ignores user input. What I had was a thread that constantly changed the state variable, while the Event thread reads the state variable. However, after one thread changes the variable, it takes several seconds for the other thread to recognize the changes, which ultimately causes the problem.

通过建立状态来修复变量 volatile

It was fixed by making the state variable volatile.

为什么Java中没有变量 volatile 默认情况下,有什么理由不使用 volatile 关键字?

Why aren't variables in Java volatile by default and what's a reason not to use the volatile keyword?

推荐答案

简而言之,易变量 - 无论是Java还是C# - 都不会在线程中本地缓存。除非您正在处理在不同内核上执行线程的多处理器/多核CPU,否则这并没有多大意义,因为它们正在查看相同的缓存。当您将变量声明为volatile时,所有读取和写入都直接来自并直接进入实际的主存储器位置;没有涉及缓存。当涉及到优化时,这会产生影响,并且不必要地(当大多数变量不需要是易变的时候)这样做会造成性能损失(尽管可能会或可能不会),但收益相对较小。

To make a long story short, volatile variables--be they in Java or C#--are never cached locally within the thread. This doesn't have much of an implication unless you're dealing with a multiprocessor/multicore CPU with threads executing on different cores, as they'd be looking at the same cache. When you declare a variable as volatile, all reads and writes come straight from and go straight to the actual main memory location; there's no cache involved. This has implications when it comes to optimization, and to do so unnecessarily (when most variables don't need to be volatile) would be inflicting a performance penalty (paltry as it may or may not be) for a relatively small gain.

这篇关于为什么Java中的变量不是默认的volatile?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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