Java memory model - can someone explain it?

前端 未结 9 1745
一个人的身影
一个人的身影 2020-11-30 01:38

For years and years, I\'ve tried to understand the part of Java specification that deals with memory model and concurrency. I have to admit that I\'ve failed miserably. Yes\

9条回答
  •  半阙折子戏
    2020-11-30 02:04

    Another attempt to provide a summary of things I understood from the answers here and from other sources (the first attempt was pretty far off base. I hope this one is better).

    Java memory model is about propagating values written to memory in one thread to other threads so that other threads can see them as they read from memory.

    In short, if you obtain a lock on a mutex, anything written by any thread that released that mutex before will be visible to your thread.

    If you read a volatile variable, anything written to that volatile variable before you read it is visible to the reading thread. Also, any write to volatile variable done by the thread that write to your variable before the write to your variable is visible. Moreover, in Java 1.5 any write at all, volatile or not, that happened on any thread that wrote to your volatile variable before the write to your volatile variable will be visible to you.

    After an object is constructed, you can pass it to another thread, and all final members will be visible and fully constructed in the new thread. There are no similar guarantees about non-final members. That makes me think that assignment to a final member acts as a write to volatile variable (memory fence).

    Anything that a thread wrote before its Runnable exited is visible to the thread that executes join(). Anything that a thread wrote before executing start() will be visible to the spawned thread.

    Another thing to mention: volatile variables and synchronization have a function that's rarely mentioned: besides flushing the thread cache and providing one-thread-at-a-time access they also prevent compiler and CPU from reordering reads and writes across sync boundary.

    None of it is new and the other answers have stated it better. I just wanted to write this up to clear my head.

提交回复
热议问题