JSON奇怪的synchronized在源代码中
我在 org.mortbay.util.ajax 包中的 jetty-util 的 JSON 类中发现了这样一个奇怪的代码,并想知道它是否是一个错误。 我唯一的猜测是从内存中读取 _deafult
变量,分享你的想法!
public static String toString(Object object)
{
StringBuffer buffer=new StringBuffer(__default.getStringBufferSize());
synchronized (buffer)
{
__default.append(buffer,object);
return buffer.toString();
}
}
I've found such a strange code in JSON class of jetty-util in org.mortbay.util.ajax package, and wondering whether it is an error or not.
My only guess is to read _deafult
variable from memory, share your thoughts guys!
public static String toString(Object object)
{
StringBuffer buffer=new StringBuffer(__default.getStringBufferSize());
synchronized (buffer)
{
__default.append(buffer,object);
return buffer.toString();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想说,他们打算编写
synchronized (__default)
而不是synchronized (buffer)
的可能性相当高。这是为了避免在调用append
期间允许对__default
进行任何更改(假设它们在进行更改时也在其他地方同步,或者其变异器函数这样做)—您还没有提到__default
是什么,这并不重要)。我完全看不出在buffer
上进行同步的任何原因。I'd say the odds are pretty high they meant to write
synchronized (__default)
instead ofsynchronized (buffer)
. This would be to avoid allowing any changes to__default
during the call toappend
(assuming they also synchronize on it elsewhere, when making changes, or that its mutator functions do — you haven't mentioned what__default
is, not that it matters much). I can't see any reason at all for synchronizing onbuffer
.这看起来确实毫无意义 - buffer 实例是在线程内构建的,因此其他线程不可能引用它。因此,
synchronized
块将始终处于无争用状态,因此不会保护任何内容,而且稍后不会有其他线程对其进行同步,因此不会产生内存一致性影响。根据预期的语义,这可能是一个错误,也可能只是重构遗留下来的一个不会导致任何问题的怪癖。 (因为就正确性而言,它相当于根本不同步,而就性能而言,它只是稍微差一点。)
从好的方面来说,Java 6 中的 Hotspot 将优化这个块。 :-)
That does look entirely pointless - the
buffer
instance is constructed right there within the thread, so no other threads could possibly have a reference to it. Hence thesynchronized
block will always be uncontended, and is thus not guarding anything, plus no other thread will synchronize on it later, so there are no memory consistency effects.Depending on the intended semantics, this may be an error, or it may just be a quirk left over from refactoring that doesn't cause any problems. (Since in terms of correctness it's equivalent to not synchronising at all, and in terms of performance it's only marginally worse.)
On the plus side, Hotspot in Java 6 will optimise this block away. :-)