Does JVM guarantee to cache not volatile variable?

2019-03-04 03:52发布

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 or may not do this, thus a programer should not depend upon JVM for this.

Thanks for the answers in advance.

3条回答
三岁会撩人
2楼-- · 2019-03-04 04:28

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.

查看更多
孤傲高冷的网名
3楼-- · 2019-03-04 04:34

No. The JVM doesn't guarantee "caching" of non-volatile fields. What implementations of JVM guarantee is how volatile fields should behave. Caching of fields is non-standard (unspecified) and can vary from JVM to JVM implementation. So, you shouldn't really rely on it (even if find out, by some way that some data is being cached by a thread)

查看更多
趁早两清
4楼-- · 2019-03-04 04:45

The recommended pattern if you need a snapshot of a field is to copy it to a local variable. This is commonly used when writing code that makes heavy use of atomics and read-modify-conditional-write loops.

查看更多
登录 后发表回答