Synchronization, When to or not to use?

前端 未结 6 717
后悔当初
后悔当初 2021-01-07 23:35

I have started learning concurrency and threads in Java. I know the basics of synchronized (i.e. what it does). Conceptually I understand that it provides mutually exclusive

6条回答
  •  悲&欢浪女
    2021-01-08 00:26

    Assuming each thread passes a different array then no synchronization is needed, because the rest of the variables are local.

    If instead you fire off a few threads all calling sortA and passing a reference to the same array, you'd be in trouble without synchronized, because they would interfere with eachother.

    Beware, that it would seem from the example that the getList method returns a new List from an array, such that even if the threads pass the same array, you get different List objects. This is misleading. For example, using Arrays.asList creates a List backed by the given array, but the javadoc clearly states that Changes to the returned list "write through" to the array. so be careful about this.

提交回复
热议问题