在什么情况下,空的同步块可以实现正确的线程语义? [英] In what situations could an empty synchronized block achieve correct threading semantics?

查看:105
本文介绍了在什么情况下,空的同步块可以实现正确的线程语义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看有关我的代码库的 Findbugs 报告,其中一个触发的模式是一个空的同步块(即 synchronized(var){} )。 文档说明

I was looking through a Findbugs report on my code base and one of the patterns that was triggered was for an empty synchronzied block (i.e. synchronized (var) {}). The documentation says:


空的同步块比大多数人认识的
更加微妙且难以正确使用,并且空的
同步块几乎从不是
更好的解决方案比较少做作的
解决方案。

Empty synchronized blocks are far more subtle and hard to use correctly than most people recognize, and empty synchronized blocks are almost never a better solution than less contrived solutions.

在我的情况下,它发生是因为块的内容已被注释掉,但是 synchronized 语句仍然存在。在什么情况下空的 synchronized 块可以实现正确的线程语义?

In my case it occurred because the contents of the block had been commented out, but the synchronized statement was still there. In what situations could an empty synchronized block achieve correct threading semantics?

推荐答案

空的同步块将等待,直到没有其他人使用该同步器。这可能是你想要的,但是因为你没有保护synchronized块中的后续代码,所以没有什么能阻止别人修改你在运行后续代码时所等待的内容。这几乎不是你想要的。

An empty synchronized block will wait until nobody else is using that synchronizer. That may be what you want, but because you haven't protected the subsequent code in the synchronized block, nothing is stopping somebody else from modifying what ever it was you were waiting for while you run the subsequent code. That's almost never what you want.

这篇关于在什么情况下,空的同步块可以实现正确的线程语义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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