同步冒险
如果我遇到一种情况,我必须使 Java 程序中的每个方法同步,这会影响我的代码的性能吗?
If i come across a situation where i will have to make each and every method in my Java program synchronized, will that affect the performance of my code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,它会影响性能。
如果您的应用程序大部分是单线程的,那么影响将非常小,因为无竞争的锁获取速度非常快(在现代 JVM 上,例如 HotSpot)。
如果您的应用程序是严重多线程的并且多个线程同时访问相同的对象,那么影响会更大。
请注意,同步每个方法并不能保证您的代码是线程安全的,您仍然可以轻松获得竞争条件。
Yes, it will influence the performance.
If your application is mostly single-threaded, then the impact will be very small, because uncontested lock acquisition is very fast (on modern JVMs such as HotSpot).
If your application is heavily multi-threaded and multiple threads access the same objects concurrently, then the impact will be larger.
Note that having every single method synchronized does not guarantee that your code is thread-safe, you can still easily get race conditions.