如何知道“同步”花费了多少时间?代码,用Java?
我有一个 Java 应用程序,它的速度没有我预期的那么快。我已经做了很多关于如何改进它的搜索,但并不幸运。
现在我正在检查代码,发现代码中有很多 synchronized
关键字。我在想他们是否花了太多时间等待锁。
有没有什么工具可以查看他们花费了多少时间?因此,如果它们确实花费了太多时间,我可以找到更好的解决方案。
I've a Java application, which is not fast enough as I expected. I've done a lot of searches of how to improve it, but not lucky.
Now I'm reviewing the code, and found there are a lot of synchronized
keyword in the code. I'm thinking if they took too much time on waiting the locks.
Is there any tool to check how much time they cost? Thus I can find a better solution if they do cost too much time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我本来打算建议 jvisualvm 的线程监视器功能,在寻找屏幕截图时,遇到了这个博客文章:检测线程争用。这比仅仅截图要好得多:)。
但无论如何,这就是:
(图片来源:上述博客文章)
I was going to suggest the Thread Monitor feature of jvisualvm and, while looking for a screen shot, ran into this blogpost: Detecting Thread Contentions. It's way better than just a screenshot :).
But here it is anyway:
(image credit: aforementioned blog post)
一个好的分析器将能够查明导致缓慢的方法,它可能与同步根本无关。另外,查看探查器中的线程状态可能会揭示是否由于同步而导致过多的等待。在任何情况下,除非无缘无故地使用同步关键字,否则为了性能而删除它可能会适得其反。
A good profiler will be able to pinpoint the methods that are causing slowness it may not be related to the synchronization at all. Also looking at the state of the threads in profiler may reveal if there is too much of waiting going on because of the synchronization. In any case unless the synchronized keyword is being used without reason it may be counter productive to remove it for the sake of performance.
同步的成本通常很小。问题通常是您在同步块中执行的操作。确保您不执行任何 IO(套接字或网络),并且理想情况下根本不进行系统调用,并且对于简单任务,锁定时间将为亚微秒。
The cost of synchronization is usually small. The problem is usually what you do in the synchronization blocks. Make sure you don't do any IO, (socket or network) and ideally no system calls at all and the lock time will be sub-microsecond for simple tasks.