Why are synchronize expensive in Java?

后端 未结 5 1003
温柔的废话
温柔的废话 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:51

    This article over at IBM actually summarizes very nicely the main points behind synchronization.

    Because of the rules involving cache flushing and invalidation, a synchronized block in the Java language is generally more expensive than the critical section facilities offered by many platforms, which are usually implemented with an atomic "test and set bit" machine instruction. Even when a program contains only a single thread running on a single processor, a synchronized method call is still slower than an unsynchronized method call. If the synchronization actually requires contending for the lock, the performance penalty is substantially greater, as there will be several thread switches and system calls required.

提交回复
热议问题