Why aren't variables in Java volatile by default?

后端 未结 6 1629
夕颜
夕颜 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:28

    While others are correct in pointing out why it would be a bad idea to default to volatile, there's another point to make: there is very likely a bug in your code. Variables seldom need to made volatile: there is always a way to properly synchronize access to variables (either by synchronized keyword, or using AtomicXxx objects from java.util.concurrency): exceptions would include JNI code manipulating these (which is not bound by synchronization directives).

    So instead of adding volatile, you may want to figure out WHY it resolved the problem. It isn't the only way to solve it, and there is probably a better way.

提交回复
热议问题