Sub topic 6
StringBuilder or StringBuffer?
This chapter assumes you know basic Java syntax, loops, methods, objects, and the String class. You should also know how to compile and run a Java program. The examples use Java 15 or later, although StringBuilder and StringBuffer are older classes.
Both StringBuilder and StringBuffer store a changeable sequence of characters. They let you append and edit text without creating a new object for every small change.
Their main difference is thread safety:
StringBuilderis not synchronized. It is usually the best choice when one thread owns the text.StringBufferis synchronized. Its methods coordinate access when multiple threads use the same object.
Why Thread Safety Matters
A thread is a separate path of execution inside a program. Two threads may try to modify the same object at nearly the same time.
A class is thread-safe when its operations remain valid under concurrent use. StringBuffer makes many of its methods thread-safe by using synchronization. Synchronization allows only one thread at a time to enter a synchronized operation on the same object.
flowchart TD
A[Several threads share text] --> B{Which class?}
B -->|One thread owns it| C[StringBuilder]
B -->|Several threads directly modify it| D[StringBuffer]
B -->|Shared work needs larger atomic actions| E[Use explicit synchronization or another design]caption: Choosing between StringBuilder and StringBuffer alt: A flowchart selects StringBuilder for single-threaded use, StringBuffer for direct shared access, and explicit synchronization for larger shared operations.
Synchronization protects individual method calls. For example, a call to buffer.append("x") is protected when the object is a StringBuffer. However, a sequence of calls is not automatically one indivisible operation.
if (buffer.length() < 100) {
buffer.append("more text");
}Another thread can change buffer between length() and append(). If those two operations must act as one unit, protect the whole sequence yourself.
How StringBuffer Differs from StringBuilder
The two classes have similar methods, including append, insert, delete, replace, and reverse.
| Feature | StringBuilder | StringBuffer |
|---|---|---|
| Methods synchronized | No | Yes |
| Best default use | One thread | Shared direct access |
| Typical performance | Faster | Some synchronization overhead |
| Concurrent modification | Unsafe | Individual methods protected |
This program uses one StringBuffer from two threads. Each call to append is protected, so the final length is predictable. The order of the characters is not predictable because the scheduler decides which thread runs first.
public class Main {
public static void main(String[] args) throws InterruptedException {
StringBuffer buffer = new StringBuffer();
Thread first = new Thread(() -> {
for (int i = 0; i < 1_000; i++) {
buffer.append('A');
}
});
Thread second = new Thread(() -> {
for (int i = 0; i < 1_000; i++) {
buffer.append('B');
}
});
first.start();
second.start();
first.join();
second.join();
System.out.println(buffer.length()); // 2000
System.out.println(buffer.indexOf("A") >= 0); // true
System.out.println(buffer.indexOf("B") >= 0); // true
}
}The calls are safe in the narrow sense that the internal character storage should not be corrupted by simultaneous append calls. The output will contain 1,000 A characters and 1,000 B characters, but their order can vary.
Why StringBuilder Is Usually Preferred
In ordinary application code, a StringBuilder is normally local to a method or owned by one thread. No other thread can access it, so synchronization would add work without solving a problem.
public static String makeReport(String[] names) {
StringBuilder report = new StringBuilder();
for (String name : names) {
report.append("- ").append(name).append('\n');
}
return report.toString();
}This method creates a builder, modifies it in one thread, and returns an immutable String. The builder does not need thread safety because it does not escape to another thread while it is being built.
Do not choose StringBuffer merely because it sounds safer. If the object is never shared, StringBuilder communicates the intended design and usually avoids unnecessary synchronization overhead.
When StringBuffer Is Appropriate
Use StringBuffer when all of these conditions are true:
- Multiple threads directly access the same mutable character sequence.
- The shared sequence itself needs synchronized method calls.
- Replacing the design with thread-local builders, immutable strings, or a queue would be less suitable.
Even then, consider whether each thread should build its own StringBuilder and combine the results later. That design often reduces contention, which happens when threads spend time waiting for the same lock.
A StringBuffer does not make every surrounding operation thread-safe. It only provides synchronization for the methods and operations defined by the class. You still need a clear ownership and locking strategy for related state.
A Practical Decision
Use StringBuilder as the default for constructing text in a method, loop, request handler, or other single-threaded section. Use StringBuffer only when shared mutable text is an intentional part of a concurrent design.
Often, the better concurrent design is to avoid sharing a builder at all:
- Give each thread its own
StringBuilder. - Let each thread produce a complete
String. - Combine those strings in a controlled step.
This approach can make ordering, testing, and performance easier to understand.
Exercise
Two threads need to append to the same object. Should you automatically use StringBuffer? Explain the limitation of its synchronization.
Show answer
Use StringBuffer only if sharing the mutable sequence is intentional. Its individual methods are synchronized, but a multi-step sequence such as checking length and then appending is not automatically atomic. For that sequence, use explicit synchronization or redesign the work to use separate builders.