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();
}
}
That does look entirely pointless – the
bufferinstance is constructed right there within the thread, so no other threads could possibly have a reference to it. Hence thesynchronizedblock 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. 🙂