ALL > Computer and Education > courses > university courses > undergraduate courses > Operating System > ZSTU-(2020-2021)-1 > student homework > 2018329621186陈魏扬 >
homework-5 Version 0
👤 Author: by 1756894282qqcom 2020-11-03 07:17:42
Here I want to introduce a relatively uncommon Java Memory Model (JMM java Memory Model). The basic thread data will be stored in a corresponding thread stack. If two threads need to interact, it must be done through variables in the shared memory. Can achieve the effect of inter-thread communication. But because the JVM can sort them arbitrarily to improve the performance of the program. At the same time the processor will optimize the instructions. These operations will cause the data to become unreliable in a multi-threaded environment. Because the order of instructions has caused some instability due to processor optimization. Analysis of visible and invisible data. When the data changes, the variable in another thread can be sensed, which is called visible. When one thread changes, the other thread cannot perceive the data at this time, which is called invisible. In the JMM shown in the figure below, when a thread changes, the variables in the shared memory are changed locally, but they are not synchronized to the shared memory variables. At this time, the local variables of thread B have not changed. The invisibility at this time led to incorrect data.

Therefore, the data needs to be synchronized in a multithreaded environment. There are two main methods to solve the problem of data out of sync.

1. The keyword synchronized. When a thread accesses this object, the synchronization operation of the object will be performed first, from the shared memory to the local memory. When the object is modified and synchronized, the local variables will be synchronized to the shared memory. In this way, the purpose of synchronizing data can be achieved.

2,

The volatile keyword can ensure the visibility of variables, because the operations on volatile are in the Main Memory, and the Main Memory is shared by all threads. The price here is that performance is sacrificed and registers or Cache cannot be used because they are not. Globally, visibility cannot be guaranteed, and dirty reads may occur.
Another function of volatile is to partially prevent the occurrence of reordering, and the operation instructions for volatile variables will not be reordered, because if reordering, visibility problems may occur.

Please login to reply. Login

Reversion History

Loading...
No reversions found.