Problems with visibility of Java variables

Source: Internet
Author: User

Transferred from: http://www.importnew.com/19434.html

Post Prerequisites

Recently, in the Oschina question and Answer section, I saw a problem with the visibility of Java variables in working and main memory: Synchorized,sleep can also achieve the purpose of volatile thread visibility, the general problem is described as follows:

123456789101112131415161718192021222324252627282930313233343536373839 packagecom.test;importjava.util.concurrent.TimeUnit;publicclass test1 {    privatestaticbooleanis = true;    publicstaticvoidmain(String[] args) {        newThread(newRunnable() {            @Override            publicvoidrun() {                int i = 0;                while(test1.is){                   i++;                   1//synchronized (this) { } 会强制刷新主内存的变量值到线程栈?                   2//System.out.println("1"); println 是synchronized 的,会强制刷新主内存的变量值到线程栈?                   3//sleep 会从新load主内存的值?                      //    try {                     //       TimeUnit.MICROSECONDS.sleep(1);                     //   }catch (InterruptedException e) {                     //      e.printStackTrace();                      //   }                            }        }).start();         try{            TimeUnit.SECONDS.sleep(1);            catch(InterruptedException e) {                e.printStackTrace();              }        newThread(newRunnable() {            @Override            publicvoidrun() {                is = false;  //设置is为false,使上面的线程结束while循环            }        }).start();    }}

Q: Why is the entire program not terminated? Why does the program terminate if you cancel any of the code blocks in the comment (All-in-one)? Synchronized will force the variable value of memory to be flushed to the thread stack? What will sleep do?

Involving knowledge interpretation
    • Volatile: This keyword guarantees the visibility of variable threads, all of which have access to variables modified by volatile, must be read from main memory, and write back to memory immediately after the modification of the working RAM, to ensure the visibility of other threads, and the same effect of the keyword is final.
    • Synchronized: All synchronization operations must be guaranteed 1, atomicity 2, visibility, so the changes that occur in the synchronization block are immediately written back to main memory
    • Sleep: This method only yields the CPU execution time and does not release the lock.
Problem analysis

Q1: Why does the program not terminate after commenting the code?

A1: Because the value of a Boolean is=true variable is loaded into its own working memory by a previous thread (called Thread A), it does not necessarily write to main memory immediately after the subsequent thread (thread B) Changes the Boolean is=false ( However, the problem should be immediately written to main memory, because the thread will exit after the execution of the is=false, even if the thread A is not immediately written to the main memory, the program will not be load into the work, so the procedure has not been terminated? This is what most of us think of, but in fact the JVM for the current hardware level has done a great degree of optimization, basically to a large extent to ensure that the working memory and main memory of the timely synchronization, equivalent to the default use of volatile. But only to the maximum extent! When the CPU resource is always occupied, the synchronization between the working memory and the main memory, that is, the visibility of the variable will not be so timely! The conclusions are verified later.

Q2: Why does the program terminate if you cancel any one of the code blocks in the comment?

A2: line number 1, 2 of the Code has a common feature, that is involved in the synchronized synchronous lock, then whether as the question author suspects synchronized会强制刷新主内存的变量值到线程栈? , 以及sleep方法也会刷新主存的变量值到线程栈呢? , in fact, we said before the synchronized will only guarantee in 同步块 , and the is variable is not in the synchronization block, so obviously this is not the result. Next we add the i++; following code behind the code:

123 for(intk=0;k<100000;k++){    newObject();}

Run again, the program terminates immediately! Why? In the above A1 We have already said that even with the optimization of the JVM, but when the CPU has been occupied, the visibility of the data is not well guaranteed, just as the above program has been circulating to i++;运算 occupy the CPU, and why add the above code after the program will stop it? Because the CPU is not a major time-consuming operation for a large number of new Object () operations, the actual duration should be on the allocation of memory (因为CPU的处理速度明显快过内存,不然也不会有CPU的寄存器了) , so the CPU is free to follow the JVM optimization benchmark, as soon as possible to ensure the visibility of the data, from main memory synchronization is variable to working memory, This eventually leads to the end of the program, which is why the sleep() method does not involve synchronization, but it can still cause the program to terminate because sleep() the method frees the CPU but does not release the lock!

End

Technology is to continue to learn and grow, adhere to the blog and technical output, for their own growth will be a great help, if there is a mistake to welcome correct, refused personal attacks.

Problems with visibility of Java variables

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.