Java memory model - can someone explain it?

前端 未结 9 1748
一个人的身影
一个人的身影 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条回答
  •  猫巷女王i
    2020-11-30 02:03

    I recently found an excellent article that explain volatile as:

    First, you have to understand a little something about the Java memory model. I've struggled a bit over the years to explain it briefly and well. As of today, the best way I can think of to describe it is if you imagine it this way:

    • Each thread in Java takes place in a separate memory space (this is clearly untrue, so bear with me on this one).

    • You need to use special mechanisms to guarantee that communication happens between these threads, as you would on a message passing system.

    • Memory writes that happen in one thread can "leak through" and be seen by another thread, but this is by no means guaranteed. Without explicit communication, you can't guarantee which writes get seen by other threads, or even the order in which they get seen.

    The Java volatile modifier is an example of a special mechanism to guarantee that communication happens between threads. When one thread writes to a volatile variable, and another thread sees that write, the first thread is telling the second about all of the contents of memory up until it performed the write to that volatile variable.

    Additional links: http://jeremymanson.blogspot.com/2008/11/what-volatile-means-in-java.html http://www.javaperformancetuning.com/news/qotm030.shtml

提交回复
热议问题