Why are synchronize expensive in Java?

后端 未结 5 999
温柔的废话
温柔的废话 2020-12-01 10:36

I am really new to Java and I read that synchronized is \"very expensive\" in Java. All I want to know is what is expensive and how is it expensive?

Th

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 10:48

    It is expensive because if you are using threads, and a number of threads have to go through a synchronized section of code, only one of them may be executed at a time.

    It is like a bottleneck.

    It is even expensive when you use a single thread, because it has to check anyway if he is allowed to run.

    If you reduce the use of synchronized segments your thread won't have to stop to see if they can run ( of course, they don't have to share data )

    A high level overview of how synchronization works may be found here

    http://img20.imageshack.us/img20/2066/monitor28synchronizatioc.png

    A Java style monitor

提交回复
热议问题