Monday, February 1, 2016

[Java] Value in JMM

See original image 
JMM has a main memory zone, and has the working memory zone for every Thread.

When you do some modification with a value  a:

  1. the thread copy the value of a from main memory to working memory aCopy
  2. do the modification or calculation 
  3. copy the result value back to main memory 
but this order is not guaranteed because the the implementation of JVM and the optimization, the 1 and 3 might be exchanged.

How to guarantee? :
       use synchronized :     before enter in synchronized block, the thread will
  project the working space to main space--->  clean the working space ----> copy the last value from main space ---> when finished the block copy the working space value to main space
    with all this we can guarantee the order 1->2->3

     use volatile key word for the variable :  whe a thread read a volatile variable, it will read the last value in main space.

No comments:

Post a Comment