Object Visibility in a Multi-threaded Program in Java

Prashant Pandey :

I was going through Java: Concurrency in Practice, and in the third chapter, the authors write:

"...There is no guarantee that operations in one thread will be performed in the order given by the program, as long as the reordering is not detectable from within that thread—even if the reordering is apparent to other threads...."

I understand that the actual order of execution of statements in one thread might not be what was written in the program (depends upon compiler optimisations and stuff). But for some reason, I cannot decipher the arcane statement written by the authors.

"...There is no guarantee that operations in one thread will be performed in the order given by the program..."-Alright. The actual order of execution of statements might differ.

"...as long as the reordering is not detectable from within that thread—even if the reordering is apparent to other threads..."-What do they mean by "....detectable from within the thread...."?

erickson :

It simply means that no re-ordering that is performed can invalidate any assertions you could make about the state visible to that thread by looking at the code.

As a simple example:

/* 1 */ x = 0;
/* 2 */ boolean c = x == 0;
/* 3 */ x = 1;

It's not permitted to move 3 before 2 because that would be detected by the value of c.

In other words, a re-ordering that might appear to create a bug when viewed by other threads is allowed, but a re-ordering that creates a bug within the thread is not allowed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=76613&siteId=1