简体   繁体   中英

What's the relationship/difference between Visibility and Ordering?

So far as I know, Visibility deals with under what condition can a thread observe/see the update to shared variable(s) by another thread. Even single-processor system can suffer from Visibility issue. While Ordering deals with in what sequence does a thread see memory operations performed by another run in another CPU. Single-processor system does NOT suffer from Ordering issue. But, I felt that sometimes so-called Ordering issue can be interpreted with the concept of Visibility,e,g.

//Thread1 runs
int data;
boolean ready;
void method1(){
  data=1;
  ready=true;
}

//Thread2 runs
void method2(){
  if(ready){
  System.out.print(data);
  }
}

If the output of the above program was "0"(rather than "1"), we can say that there was an Ordering issue(ie Reordering)---the write to ready appeared to be occurred before the write to data . However, I think we can also interpret this output as a result of Visibility: Thread2 first saw the update to ready by Thread1, and then data ,possibly due to Store Buffer flush to CPU Cache, And if the print(data) was executed before Thread2 saw update to data , then we got the output "0". Taking this into account, I just wonder what's is the difference/relationship between Visibility and Ordering?

Yes, ordering and visibility are related issues.

  • Visibility is about whether / when one thread sees the results of memory writes performed by another thread

  • Ordering is about whether the order in which updates are seen by the second thread matches the (program) order in which the first thread wrote them.

The Java memory model doesn't directly address the ordering of writes. Any constraints on order are (as you hypothesize) a consequence of the visibility rules: these are specified in the JLS. This includes the case where you use volatile variables to effectively inhibit reordering.

It is also worth noting that the reordering of writes (from the perspective of a second thread) can happen whenever the JLS memory model does not require visibility. Correct synchronization will guarantee visibility at the point of synchronization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM