Why aren't variables in Java volatile by default?

后端 未结 6 1624
夕颜
夕颜 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-30 07:36

    Volatiles are really only needed when you're trying to write low-level thread-safe, lock-free code. Most of your code probably shouldn't be either thread-safe or lock-free. In my experience, lock-free programming is only worth attempting after you've found that the simpler version which does do locking is incurring a significant performance hit due to the locking.

    The more pleasant alternative is to use other building blocks in java.util.concurrent, some of which are lock-free but don't mess with your head quite as much as trying to do it all yourself at a low level.

    Volatility has its own performance costs, and there's no reason why most code should incur those costs.

提交回复
热议问题