English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Sometimes compiler and processor optimization can lead to runtime being different from what we expect, for this reason, Java imposes some restrictions on compilers and processors, JAVA memory model (JMM) abstracts these, so when writing code, we don't have to consider so many low-level details, and ensures that 'as long as the program is written following the rules of JMM, its running result will definitely be correct'.
JMM's abstract structure
In Java, all instances and static variables are stored in heap memory, which can be shared between threads, and this part is also calledshared variables. And local variables, method definition parameters, and exception handling parameters are in the stack, and stack memory is not shared between threads.
And due to compiler and processor optimization, it can cause visibility problems with shared variables, like in multi-core processors (multi-processor), threads can be executed on different processors, andProcessor cache inconsistency can cause visibility problems with shared variables, it is possible for two threads to see the same variable with different values.
JMM abstracts these hardware optimizations into each thread having its own local memory. When you need to read and write shared variables, copy one from the main memory to the local memory. When writing shared variables, write them first to the local memory and then refresh them to the main memory at a later time. When reading shared variables again, they will only be read from the local memory.
So thread communication between threads needs to go through two steps:
Writing thread: refresh local memory to main memory Reading thread: read the updated value from main memory
So in writing-There is a delay between reading and writing: when is the local memory refreshed to the main memory? This leads to visibility problems, and different threads may see different shared variables.
happens-antes
Literally, happens-The meaning of before is 'happens before'. This is the rule formulated by Java for the execution order of the program, and synchronization must follow this rule to implement. This way, the programmer only needs to write the correct synchronization program, happens-before ensures that the running result will not be wrong.
ocorre A-before B, not only does it mean that A is executed before B, but also that the execution result of A is visible to B, which ensures visibility.
ocorre A-before B, A does not necessarily have to be executed before B. If A and B alternate, the execution result can still be correct, allowing the compiler and processor to optimize and reorder. Therefore, as long as the program result is correct, there is no problem with how the compiler and processor optimize and reorder, they are all good.
happens-before rule
program order rule: in a thread, the operations before happens-rule for operations after before: unlocking happens for the same lock-before lock volatile field rule: writing volatile variables, happens-transitividade para qualquer leitura subsequente dessa variável volatile 'antes': A 'ocorre'-antes do B, ocorre B-antes do C, ocorre A-regra antes do ThreadB.start(): se o ThreadA executar ThreadB.start(), então o ThreadB.start() 'ocorre'-regra antes do ThreadB.start(): se o ThreadA executar ThreadB.join(), todas as operações do ThreadB 'ocorrem'-antes do ThreadB.join()
Este exemplo ajuda a entender 'ocorre'-antes
double pi = 3.14; //A double r = 1.0; //B double área = pi * r *r; //C
há três 'ocorre' aqui-regra de relação antes do, regra1,2é a regra de ordem do programa, regra3é derivado da regra transitiva:
ocorre A-antes do B, ocorre B-antes do C, ocorre A-antes do C
C depende de A e B, mas nem A nem B dependem de ninguém. Portanto, mesmo que A e B sejam reordenados, o resultado da execução não mudará. Essa reordenação é executada pelo JMM.
Os resultados das duas sequências de execução a seguir são corretos.
Aqui está todo o conteúdo que reunimos sobre as experiências de aprendizado do modelo de memória Java JMM. Para mais perguntas, você pode deixar comentários abaixo. Obrigado pelo seu apoio ao tutorial Yell.
Declaração: O conteúdo deste artigo é extraído da internet, pertence ao autor original, foi contribuído e carregado voluntariamente pelos usuários da internet. Este site não possui direitos de propriedade, não foi editado manualmente e não assume responsabilidade por questões legais relacionadas. Se você encontrar conteúdo suspeito de violação de direitos autorais, por favor, envie um e-mail para: notice#oldtoolbag.com (ao enviar e-mail, substitua # por @ para denunciar e forneça provas relevantes. Apenas após a verificação, o site deletará o conteúdo suspeito de violação de direitos autorais.)