Does JVM guarantee to cache not volatile variable?

后端 未结 3 1305
囚心锁ツ
囚心锁ツ 2021-01-27 00:42

Does JVM guarantee to cache not volatile variable ?

Can a programer depend upon on JVM to always cache non-volatile variables locally for each thread.

Or JVM may

3条回答
  •  不要未来只要你来
    2021-01-27 01:31

    The java language spec is pretty clear about volatile:

    The Java programming language provides a second mechanism, volatile fields, that is more convenient than locking for some purposes.

    A field may be declared volatile, in which case the Java Memory Model ensures that all threads see a consistent value for the variable (§17.4).

    That's it. You got a special keyword defining this special semantic. So, when you think the other way round: without that special keyword, you can't rely on any special semantics. Then you get what the Java Memory Model has to offer; but nothing more.

    And to be fully correct - there is of course Unsafe, allowing you to tamper with memory in unsafe ways with very special semantics.

提交回复
热议问题