StringBuffer and how hard it is to get rid of legacy code

In 2006, Java 5.0 was released with StringBuilder, a more lightweight 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;

How many objects does this create?
public class Main {
    public static void main(String... args) {
        System.out.println("Hello " + "world");
    }
}

Peter Lawrey

Peter Lawrey is a Java Champion and Oracle Code One alumnus. Peter likes to inspire developers to improve the craftsmanship of their solutions and his popular blog “Vanilla Java” has had over 4 million views. Peter is the founder and architect of Chronicle Software. He has one of the top number of answers for Java and JVM on StackOverflow.com (~13K).