Why aren't variables in Java volatile by default?

后端 未结 6 1630
夕颜
夕颜 2020-12-30 07:05

Possibly similar question:

Do you ever use the volatile keyword in Java?


Today I was debugging my game; It had a very difficult threading problem that w
6条回答
  •  执念已碎
    2020-12-30 07:37

    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.

提交回复
热议问题