Reputation: 4682
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...."?
Upvotes: 4
Views: 312
Reputation: 269897
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.
Upvotes: 3
Reputation: 426
I would say that they mean that the thread that is "detecting" the ordering is just going to follow the order of execution but not all threads will behave in this manner.
Upvotes: 1
Reputation: 13153
I'm having to guess a little bit here, but this is my take on it: you write a program that creates different threads for processing; you create thread A, start it, create thread B, start it, etc.
There is no guarantee that thread A will run before thread B. It is likely, probably even most common, but part of concurrent programming is eliminating this kind of assumption from your thinking. If ANY PART of the logic of B depends on ANY PART of the logic of A executing first, then you need to do programming of your own to guarantee that -- the fact that you have created A before B, nor the fact that you've done anything else outside thread coordination logic, will guarantee that any part of A will execute before any part of B.
As for "detectable within the thread", I assume they mean some kind of semaphore, variable, lock, etc. that allows one thread to know something about the completion of some other thread.
I think it's confusing for them to use "the order given by the program" -- that's really ambiguous, especially to people just starting to try to think about concurrent programming. It does not mean that statements can be reordered regardless of where they are.
Does that help?
Upvotes: 1