问题描述
我正在查看有关我的代码库的报告,其中一个触发的模式是一个空的同步
块(即 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:
在我的情况下,它发生是因为块的内容已被注释掉,但是 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.
这篇关于在什么情况下,空的同步块可以实现正确的线程语义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!