question about so-called "memory consistency errors"
I'm new to java threads and synchronization. I'm going through a tutorial here and I'm confused about what it says here.
Suppose a simple int field is defined and initialized:
int counter = 0;
The counter field is shared between two threads, A and B. Suppose 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
I'm not sure why counter would still be 0 after thread A has incremented it. Isn't it just one variable? If thread A increments it, it becomes 1, and every other thread (or object, or any part of the program) should see the value 1 stored there when it tries to access it... no? It seems pretty clear from the wording that thread B prints out the value of counter "shortly afterwards" meaning that the increment and the printing aren't executed exactly at the same time, so the increment should be done before the printing starts. The only way to make sense of this, to me, is to assume that each thread gets its own copy of counter... is that what's going on? Or maybe I just need to understand what "visible" means.