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)
{
StringB开发者_如何学编程uffer buffer=new StringBuffer(__default.getStringBufferSize());
synchronized (buffer)
{
__default.append(buffer,object);
return buffer.toString();
}
}
I'd say the odds are pretty high they meant to write synchronized (__default)
instead of synchronized (buffer)
. This would be to avoid allowing any changes to __default
during the call to append
(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 on buffer
.
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 the synchronized
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. :-)
精彩评论