Regarding the importance of synchronization

This might be a dumb question, but I'm new to multi-threaded programming in Java. I created 4 threads and then brought the run method to them. In the run method, I use an array and assign values ​​to these indices. I see that each thread maintains its own copy of the array, and there is no unsafe behavior. I just wanted to know that in this case it is important to use synchronization? (I thought it was used to control access to the shared resource. Is there an array that should be a shared data structure here?)

+3
source share
4 answers

No - if each thread uses its own copy of the array, then you have four separate arrays that contain the same data, but sharing does not occur.

Sharing would be if you had one array, and all four threads worked on this array, and at least the potential for two threads could use the same data at the same time. In this case, you will need synchronization to ensure that only one of them tried (for example) to write to any particular place at any given time (or that if someone read and still wrote that the recording was atomically read occurs either completely before the recording, or completely after it - but they will not overlap).

+2
source

, , ( , , ), .

+1

, .

, , " " ; Thread.run() ; Thread.start() ( run() ).

0

Does it depend on what you mean by “In the start method, I use an array” (underscore when used)? If you passed an array reference to a stream, then yes, synchronization will prevent simultaneous access to the array. However, if you create an array instance in a stream, then you have 4 separate array instances, and synchronization has no effect.

0
source

Source: https://habr.com/ru/post/1773067/


All Articles