Thread Caching and Java Memory model

前端 未结 4 1939
野的像风
野的像风 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条回答
  •  猫巷女王i
    2020-11-29 03:00

    CPUs have multiple caches. It is these hardware caches which might have inconsistent copies of the data. The reason they might be inconsistent is that keeping everything consistent can slow down your code by a factor of 10 and ruin any benefit you get from having multiple threads. To get decent performance you need to be selectively consistent. The Java Memory Model describes when it will ensure the data is consistent, but in the simplest case it doesn't.

    Note: this is not just a CPU issue. A field which doesn't have to consistent between threads can be inlined in the code. This can mean that if one thread changes the value another thread might NEVER see this change as it has been burnt into the code.

提交回复
热议问题