StringBuffer and how hard it is to get rid of legacy code
In 2006, Java 5.0 was released with StringBuilder, a more light weight and sane version of StringBuffer. The Javadoc for Java 5.0 for StringBuffer notes
As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.
Having synchronized
on StringBuffer
was never a good idea. The basic problem is that one operation is never enough. A single .append(x)
is not useful without another .append(y)
and a .toString()
. While individual methods were thread safe, you couldn’t make multiple calls to StringBuffer without race conditions. Your only option is external synchronized or using ThreadLocal
StringBuilders (or more obviously create them on demand)
So more than ten years later, no one uses StringBuffer!? Certainly not for new functionality!?
How many objects does this create?
As I have noted before, the JVM creates many objects on start up or starting core libraries. Much more than you might expect making question like the following are a bit meaningless;
public class Main {
public static void main(String... args) {
System.out.println("Hello " + "world");
}
}