This might be a dumb question to ask but I am new to multi-threaded programming in Java.I created 4 threads and then invoked the run method on them.In the run method I am using an array and am assigning values to it's indices.I see that each thread is maintaining it's own copy of the array and there is no thread-unsafe behavior. I just wanted to know that in this case what is the significance of using synchronization?(I thought it was used to control access to a shared resource.Isn't the array supposed to be a shared data structure here?)
No -- if each thread uses its own copy of the array, then you have four separate arrays that happen to contain the same data, but no sharing is happening.
Sharing would be if you had one array, and all four threads operated on that array, with at least the potential for two threads to use the same data at the same time. In such a case you would need synchronization to assure that only one of them tried (for example) to write to any specific location at any one time (or that if one was reading and another writing, that the writing was done atomically, with the read happening either completely before the write, or else completely after it -- but the two would not be allowed to overlap).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With