Let's say I have two arrays:
int[] array1 = new int[2000000];
int[] array2 = new int[2000000];
I stick some values into the arrays and then want to add the contents of array2 to array1 like so:
for(int i = 0; i < 2000000; ++i) array1[i] += array2[i];
Now, let's say I want to make processing faster on a multi-processor machine, so instead of just doing a loop like above, I create two threads. One of which I have process the first 1000000 elements in the array, the other I have process the last 1000000 elements in the array. My main thread waits for those two threads to notify it that they are finished, and then proceeds to use the values from array1 for all kinds of important stuff. (Note that the two worker threads may not be terminated and may be reused, but the main thread will not resume until they have both notified it to do so.)
So, my question is: How can I be sure that the main thread will see the modifications that the two worker threads made to the array? Can I count on this to happen or do I need to go through some special procedure to make sure the worker threads flush their writes to the array and the main thread discards its cached array values?

1 answers
Although the two threads have their own stack, they share the same heap where the arrays (as reference types) are stored.
You can certainly assume that writes to memory (whatever its physical form) will have taken place before that memory is next read. As the threads are reading and writing from different parts of the two arrays, there's no need to worry about synchronization or atomicity (though reading/writing 4 byte integers is atomic on x86 processors).
There's also no need to worry about the arrays being moved in memory if a garbage collection takes place in the middle of the operations. Large objects (above 85K) are never moved anyway but, even if they were, this wouldn't be a problem as the GC suspends all running threads whilst doing its work.
answered one year ago by:
17279