Sub topic 6
StringBuilder or StringBuffer?
StringBuilder and StringBuffer look almost the same. They have the same methods, the same constructors, and the same growth behavior. This chapter covers the one real difference, thread safety, and what that difference does and does not buy you. It assumes you can use StringBuilder with append, insert and toString as covered earlier in this tutorial. It also assumes you know what a thread is and have seen Thread.start() and join().
The Working Model
Both classes extend the same internal base class, AbstractStringBuilder. Each keeps a mutable array of characters and a count of how many are in use, and each exposes the same operations. They differ in one respect:
StringBufferhas existed since JDK 1.0. Its public methods aresynchronized, so only one thread at a time can run any of them on a given instance.StringBuilderwas added in JDK 1.5 as a drop-in replacement. Its methods are not synchronized.
Synchronization is not free. A synchronized method must acquire and release a lock (the instance's monitor) on every call. When no other thread is competing for that lock, the cost is small on a modern JVM. It is still not zero, and it buys nothing if the object never leaves one thread.
| Property | StringBuilder | StringBuffer |
|---|---|---|
| Since | Java 1.5 | Java 1.0 |
| Methods synchronized | No | Yes |
| Safe for concurrent modification | No | Each single call, yes |
| Typical use | Local variables, single-threaded code | Legacy code, rarely new code |
| API | Same | Same |
Why Most Builders Never Need a Lock
A thread-safe class only matters if several threads can reach the same object. Most builders are created inside a method, filled, and converted to a String:
static String describe(int[] values) {
StringBuilder sb = new StringBuilder();
for (int v : values) {
sb.append(v).append(' ');
}
return sb.toString().trim();
}The builder here is a local variable. No other thread can see it, because the reference never leaves the method. This is called thread confinement. A confined object needs no locking, and StringBuilder is the right choice.
The String that toString() returns is immutable, so you can share it freely between threads. The usual pattern is to build in one thread and publish the finished String.
What Goes Wrong Without Synchronization
StringBuilder.append is not one atomic step. It checks whether the buffer has room, grows it if needed, copies the new characters, and then updates the count. If two threads interleave those steps on the same instance, you get a data race. The symptoms are:
- Lost appends, so the final length is smaller than the number of characters you added.
- Corrupted content, such as
nullcharacters ('\u0000') where text should be. - An
ArrayIndexOutOfBoundsExceptionthrown from insideappend.
The program below makes the difference visible. Two threads each append "x" 100,000 times to a shared builder, and then to a shared buffer.
import java.util.function.Consumer;
import java.util.function.IntSupplier;
public class SharedBuffer {
static int run(Consumer<String> appender, IntSupplier length)
throws InterruptedException {
Runnable task = () -> {
for (int i = 0; i < 100_000; i++) {
appender.accept("x");
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
return length.getAsInt();
}
public static void main(String[] args) throws InterruptedException {
StringBuilder builder = new StringBuilder();
StringBuffer buffer = new StringBuffer();
System.out.println("StringBuilder: " + run(s -> builder.append(s), builder::length));
System.out.println("StringBuffer: " + run(s -> buffer.append(s), buffer::length));
}
}The StringBuffer line always prints 200000. The StringBuilder line usually prints a smaller number, and the number changes from run to run. On some runs a thread dies with an ArrayIndexOutOfBoundsException, and its stack trace appears on standard error. On a lucky run the result may even be correct. A race that sometimes passes is the dangerous kind, because tests can pass and production can still fail.
Reading builder.length() after join() is safe. join() creates a happens-before relationship, which means everything the finished thread wrote is visible to the thread that joined it. The race is in the concurrent appends, not in the final read.
Synchronized Methods Do Not Make Compound Operations Atomic
StringBuffer guarantees that each individual method call is atomic. It does not guarantee that a sequence of calls is atomic. This is the most common misunderstanding about the class.
Consider building a comma-separated list from several threads:
StringBuffer log = new StringBuffer();
void add(String entry) {
if (log.length() > 0) { // call 1: read
log.append(", "); // call 2: write
}
log.append(entry); // call 3: write
}Each of the three calls is synchronized. The method as a whole is not. Thread A can check length(), then thread B can append its entry, then thread A appends ", ". Entries can end up in an order you did not intend, or with a separator in the wrong place. Even the chained form sb.append(a).append(b) is two separate lock acquisitions, so another thread can slip text between a and b.
Two details of the problem are worth knowing:
StringBufferstill protects its internal state. You will not see array corruption, only logical interleaving.- The fix is to make the whole sequence one critical section, which
StringBuffercannot do for you.
Fix: Guard the Whole Operation Yourself
Put the builder behind a class that owns the lock. Once you do that, StringBuilder is enough, because every access happens under your lock:
public class SafeLog {
private final StringBuilder text = new StringBuilder();
public synchronized void add(String entry) {
if (text.length() > 0) {
text.append(", ");
}
text.append(entry);
}
public synchronized String snapshot() {
return text.toString();
}
public static void main(String[] args) throws InterruptedException {
SafeLog log = new SafeLog();
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
log.add("a");
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
// 2000 entries of length 1, plus 1999 separators of length 2
System.out.println(log.snapshot().length()); // 1999 * 2 + 2000 = 5998
}
}The output is always 5998: 2000 one-character entries and 1999 two-character separators (", "). The class never hands out its builder, so no outside code can bypass the lock. Hiding the mutable object and exposing only synchronized methods is the same idea as thread confinement, applied to a shared object.
You can also lock on a StringBuffer yourself with synchronized (log) { ... }, because its methods synchronize on this. That works, but it relies on an implementation detail. A private lock object or synchronized methods in your own class states the intent more clearly.
Reading While Another Thread Writes
Snapshots have the same problem. Calling toString() on a shared StringBuffer gives you a consistent string for that instant. Between two calls, though, the content may change:
int n = buffer.length();
char last = buffer.charAt(n - 1); // may throw if another thread called setLengthEach call is safe, but the pair is not. The same rule applies: if your logic needs more than one call to see a stable state, you need your own lock around all of them.
Decision Flow
For most real programs the first question ends the discussion. When it does not, the second option is often better than sharing. Have each worker build its own text and combine the results at the end with String.join or a Collectors.joining stream. That removes contention instead of managing it.
Common Errors and Misconceptions
- Using
StringBuffer"to be safe" in single-threaded code. It adds locking cost and signals a thread-safety need that does not exist, which can mislead readers. - Believing
StringBuffermakes a whole class thread-safe. It protects single calls only. A check-then-act sequence is still a race. - Sharing a
StringBuilderthrough a field or static variable without noticing. Fields likeprivate static final StringBuilder SBare shared by every thread that calls the method. - Assuming the compiler's string concatenation uses
StringBuffer. The+operator never does. It compiles toStringBuildercode, or in Java 9 and later to aninvokedynamiccall that uses its own strategy. Neither introduces locking. - Comparing builders with
equals. Neither class overridesequals, sosb1.equals(sb2)is an identity comparison. ComparetoString()results, usecontentEquals, or on Java 11 and later usecompareTo. - Ignoring how old APIs shaped habits. Some methods, such as
Matcher.appendReplacement, originally accepted onlyStringBuffer. Java 9 addedStringBuilderoverloads, so new code does not needStringBufferthere.
When StringBuffer Is Still the Right Answer
New code rarely needs StringBuffer, but a few cases remain:
- A legacy API or interface requires a
StringBufferparameter or return type. - A single shared text buffer receives independent single-call updates from many threads, and you do not want to write a wrapper class. Each call is atomic, so the state stays valid.
- You are maintaining old code and changing the type would ripple through many signatures with no benefit.
In all other situations, choose StringBuilder and add your own synchronization only where sharing is real.
Key Points
StringBuilderandStringBufferhave the same API. OnlyStringBuffersynchronizes each method.- Most builders are local, so they are confined to one thread and need no locking.
- Unsynchronized sharing can lose appends, corrupt content or throw exceptions, and the symptoms vary from run to run.
- Synchronized single calls do not protect sequences of calls. Guard compound operations with your own lock.
- Prefer one builder per thread and merge the finished
Stringvalues over sharing one builder.
Exercise
A teammate replaces StringBuilder with StringBuffer in a method that appends to a shared field, saying "now it's thread-safe". The method does if (buf.length() > 0) buf.append(';'); buf.append(item);. Explain whether the code is now correct, and give one way to fix it.
Show answer
It is not correct. Each call is synchronized, but the sequence of length(), append(';') and append(item) is not atomic. Another thread can append between the length check and the writes, so separators and items can end up out of order or doubled. Fix it by making the whole sequence one critical section, for example by wrapping it in a synchronized method of a class that owns the builder (a StringBuilder is then enough), or by using synchronized (buf) { ... } around all three statements.
Exercise
You are writing a method that formats a report line from a list of values, and it is called concurrently from many request threads. Each call creates its own builder. Which class should you use, and why?
Show answer
Use StringBuilder. The builder is a local variable, so it is confined to one thread and no other thread can touch it. Locking would only add overhead. The finished String returned by toString() is immutable and safe to share across threads.