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");

Want access to exclusive Chronicle content?

The Chronicle Community is now live, hit the button below and join the community, for free! You'll get exclusive access to blogs, guides and video content. Join today!

Peter Lawrey

Most answers for Java and JVM on (~13K), "Vanilla Java" blog with four million views, founder of the Performance JUG, Java Champion.
Posted in ,

Want more from Chronicle? Subscribe today!

Something went wrong. Please check your entries and try again.