Errors that result from inconsistent views of shared memory.
Memory consistency errors occur when different threads have inconsistent views of what should be the same data.
The results of a write by one thread are guaranteed to be visible to a read by another thread only if the write operation happens-before the read operation.
The key to avoiding memory consistency errors is understanding the happens-before relationship.
- A simple int field is defined and initialized:
int counter = 0;
- The counter field is shared between two threads, A and B.
- Thread A increments counter:
- Then, shortly afterwards, thread B prints out counter:
If the two statements had been executed in the same thread, it would be safe to assume that the value printed out would be “1”. But if the two statements are executed in separate threads, the value printed out might well be “0”, because there's no guarantee that thread A's change to counter will be visible to thread B — unless the programmer has established a happens-before relationship between these two statements. (ie between increment and println)