为什么在Java中同步昂贵? [英] Why are synchronize expensive in Java?

查看:160
本文介绍了为什么在Java中同步昂贵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的新手,我读到Java中的synchronized非常昂贵。我想知道的是什么是昂贵的,它是如何昂贵的?
谢谢。

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? Thanks.

推荐答案

也许它没有你想象的那么糟糕

过去很糟糕(这可能就是为什么你读到它非常昂贵)。这些模因可能需要很长时间才能消亡

It used to be terrible (which is possibly why you read that it was "very expensive"). These memes can take a long time to die out

这里是关于它的好文章


同步有多贵?



由于涉及缓存刷新和失效的规则,Java语言中的同步块通常比许多平台提供的关键部分设施更昂贵,这些平台通常使用原子测试和设置位机器指令。即使程序只包含在单个处理器上运行的单个线程,同步方法调用仍然比非同步方法调用慢。如果同步实际上需要争用锁定,则性能损失要大得多,因为需要多个线程切换和系统调用。

How expensive is 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.

幸运的是,持续改进了JVM既提高了整体Java程序性能,又降低了与每个版本同步的相对成本,并且预计将来会有所改进。此外,同步的性能成本经常被夸大。一个众所周知的消息来源指出,同步方法调用比非同步方法调用慢50倍。虽然这种说法可能是正确的,但它也具有误导性,并导致许多开发人员即使在需要的情况下也要避免同步。

Fortunately, continuous improvements in the JVM have both improved overall Java program performance and reduced the relative cost of synchronization with each release, and future improvements are anticipated. Further, the performance costs of synchronization are often overstated. One well-known source has cited that a synchronized method call is as much as 50 times slower than an unsynchronized method call. While this statement may be true, it is also quite misleading and has led many developers to avoid synchronizing even in cases where it is needed.

话虽如此 - 并发编程仍然可能很慢,但现在并非如此纯粹是Java的错误。精细锁定和粗锁定之间存在权衡。太粗糙显然是不好的,但它也可能太精细,因为锁具有非零成本。

Having said that - concurrent programming can still be slow, but not so much of it is purely Java's fault now. There is a tradeoff between fine and coarse locking. Too coarse is obviously bad, but it's possible to be too fine too, as locks have a non zero cost.

考虑争用下的特定资源非常重要。机械硬盘就是一个例子,其中更多的线程可以导致更差的性能。

It's important to consider the particular resource under contention. Mechanical hard disks are an example where more threads can lead to worse performance.

这篇关于为什么在Java中同步昂贵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆