Thread Caching and Java Memory model

前端 未结 4 1940
野的像风
野的像风 2020-11-29 02:21

I\'m trying to understand the Java memory model and threads. As fas has I understand, each thread has a local copy of the \"main\" memory. So if one thread tries to change a

4条回答
  •  一个人的身影
    2020-11-29 03:07

    A thread doesn't have a local copy of memory. Part of the memory the thread reads/writes could be from a cache, instead of main memory. Caches do not need to be in sync with each other, or in sync with main memory. So this is where you can observe inconsistencies.

    So if one thread tries to change a int variable for example of some object it caches the int variable and if it changes it other thread might not see the change.

    That is correct. The Java Memory model is defined in happens before rules, e.g. there is a happens before rule between a volatile write of field x and a volatile read of field x. So when a write is done, a subsequent read will see the value written.

    Without such a happens before relation, all bets are off (also instruction reordering can make life complicated when there is no happens before rule).

    If thread caches a reference to an object any change to the state of the object are also not visible to other threads? Why?

    It could be visible.. it could also not be visible. Without a happens before rule, all bets are of. The reason why is that otherwise a lot of optimizations like hardware tricks to speed things up, or compiler tricks would not be allowed. And of course, always keeping memory in sync with the cache, would reduce performance.

提交回复
热议问题