Synchronization, When to or not to use?

前端 未结 6 720
后悔当初
后悔当初 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:27

    Synchronization as you have correctly figured has an impact on the throughput of your application, and can also lead to starving thread.

    All get basically should be non blocking as Collections under concurrency package have implemented.

    As in your example all calling thread will pass there own copy of array, getList doesn't need to be synchronized so is sortA method as all other variables are local.

    Local variables live on stack and every thread has its own stack so other threads cannot interfere with it.

    You need synchronization when you change the state of the Object that other threads should see in an consistent state, if your calls don't change the state of the object you don't need synchronization.

提交回复
热议问题