volatile

volatile

The detailed explanation of volatile is reproduced from: http://www.cnblogs.com/dolphin0520/p/3920373.html

Three characteristics of shared data security: atomicity, visibility, and orderliness.
When the above three characteristics are guaranteed, multi-threaded concurrency will not affect the data.

Volatile guarantees visibility and ordering, but not atomicity. Therefore, when there are volatile modified variables, in multi-threaded programming, it is necessary to take into account the atomicity of the overall variable to ensure the security of shared data.

Question1: What is the working principle of volatile?
        Observing the assembly code generated when the volatile keyword is added and the volatile keyword is not added, it is found that when the volatile keyword is added, an additional lock prefix instruction will be added.
1: volatile guarantees reordering. It ensures that the instruction after it will not be queued to the position before the lock-marked instruction when the instruction is reordered, and the previous instruction will not be queued after it; that is, when the instruction with the lock prefix is ​​executed, it is before it. operations have been completed.
2: volatile guarantees visibility. It forces the modification of the cache to be written to main memory immediately, and at the same time marks the contents of the cache line of other threads as invalid, so when other threads manipulate the variable, they must re-read the value of the variable from the main memory.

question2: The difference between
volation and synchronized? The difference between volatile and synchronized:
1: volatile is lightweight and can only modify variables.
      Synchronized is heavyweight and can modify methods and code blocks.
2: Volatile can only guarantee the visibility and ordering of data, and cannot be used to guarantee atomicity, because concurrent access to volatile-modified variables by multiple threads will not block. (Atomicity is not guaranteed: either all or none)
      synchronized not only guarantees visibility, but also guarantees atomicity, because only the thread that has acquired the lock can enter the critical section, thus ensuring that all statements in the critical section are fully implement. Blocking occurs when multiple threads compete for synchronized lock objects.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326120473&siteId=291194637