1. Introduction
Java provides three commonly discussed types for working with text:
Stringrepresents immutable text. Once aStringobject is created, its character sequence cannot be changed.StringBuilderrepresents mutable text and is generally preferred when one thread assembles a string.StringBufferalso represents mutable text, but its public methods are synchronized to support safe access to a shared instance by multiple threads.Premium Video
This video is available to Premium members or users who have purchased the course.
Sign in to Unlock
StringBuffer is the thread-safe counterpart to StringBuilder. It offers a very similar API, including append(), insert(), delete(), replace(), reverse(), setLength(), and capacity-management methods. The key distinction is synchronization: individual public method calls acquire the buffer object's intrinsic lock.
That protection has a cost. For local text-building work, StringBuilder is usually the better default. StringBuffer is useful when multiple threads genuinely need to operate on the same mutable buffer and the simpler synchronized API fits the design.
This guide covers the history, internal model, important methods, thread-safety guarantees, compound operations, performance, practical examples, common pitfalls, and decision rules.
2. Learning Objectives
After studying this guide, you should be able to:
- Explain why
StringBufferis mutable andStringis immutable. - Describe the relationship between
StringBuffer,StringBuilder, and their shared implementation. - Understand what
synchronizedguarantees for a single method call. - Use common
StringBuffermethods and capacity controls. - Recognize why individually synchronized calls do not automatically make a multi-step algorithm atomic.
- Choose between
StringBuffer,StringBuilder, and alternative concurrency designs. - Identify performance costs and avoid common thread-safety mistakes.
3. What Is StringBuffer?
StringBuffer is a mutable sequence of characters in java.lang. Because it belongs to java.lang, it does not require an import statement.
Unlike a String, a StringBuffer can be updated after construction. Calling append() adds text to the existing buffer, while delete() can remove a range of characters. These operations change the logical content of the same buffer object.
Expected output
Order #105 confirmed
Length: 20
Capacity: 34
The exact capacity follows the buffer's growth rules and the initial capacity. The important distinction is that length() reports characters currently in use, whereas capacity() reports how many characters can fit before the internal storage must grow.
Key characteristics
- Mutable: methods can change the contents of the same object.
- Synchronized public methods: individual calls coordinate through the object's intrinsic lock.
- Dynamic capacity: the internal buffer can grow when more room is needed.
- StringBuilder-like API: most everyday text-building methods have matching equivalents.
- Conversion to String:
toString()produces an immutableStringsnapshot of the current contents.
4. A Brief History and Class Relationship
StringBuffer was introduced with Java 1.0 in 1996. At the time, it was the JDK's main mutable string class, and its public methods were designed to be synchronized. Java 5 introduced StringBuilder in 2004. StringBuilder offers a similar API without built-in synchronization, improving performance for the common single-threaded case.
Both classes share buffer-management implementation through the package-private AbstractStringBuilder class. This shared implementation handles much of the underlying character storage and mutation logic.
The practical rule is straightforward: modern code generally uses StringBuilder unless the buffer is shared among threads and synchronized method-level access is specifically useful. Legacy code may use StringBuffer because it predates Java 5 or because its design relies on synchronized operations.
5. Why StringBuffer Is Thread-Safe
Every Java object has an intrinsic lock, also called a monitor. A synchronized instance method acquires the monitor associated with this before executing and releases it when the method exits, including when it exits by throwing an exception.
For a single StringBuffer instance, synchronized methods prevent two threads from executing those synchronized methods on that same object simultaneously.
This supports two important properties:
- Mutual exclusion for an individual call: two
append()calls on the same buffer do not concurrently update its internal state. - Memory visibility: when one thread releases the monitor and another thread subsequently acquires that same monitor, the Java Memory Model establishes a happens-before relationship. The second thread can observe writes made before the first thread released the lock.
Conceptual lock flow
The exact order in which waiting threads acquire the monitor is not generally guaranteed. Synchronization ensures mutual exclusion for protected operations; it does not promise a particular scheduling order.
6. StringBuffer and StringBuilder Have Nearly the Same API
For ordinary text construction, you can often replace StringBuilder with StringBuffer without changing the method calls or resulting text. Both support methods such as:
append(...)insert(...)delete(start, end)deleteCharAt(index)replace(start, end, str)reverse()charAt(index)setCharAt(index, ch)length()setLength(newLength)capacity()ensureCapacity(minimumCapacity)trimToSize()toString()
The key difference is the synchronization behavior. StringBuffer synchronizes its public methods, including methods that read its state such as length(), capacity(), and toString(). StringBuilder does not provide that built-in thread-safety guarantee.
Expected output
Learning StringsEach call works on the same mutable buffer. The example illustrates the shared API; it does not by itself demonstrate concurrent execution.
7. Common Constructors, Length, and Capacity
The commonly used constructors include:
| Constructor | Purpose |
|---|---|
new StringBuffer() | Creates an empty buffer with a default capacity of 16 characters. |
new StringBuffer(int capacity) | Creates an empty buffer with the requested initial capacity. |
new StringBuffer(String str) | Starts with the supplied text; the initial capacity is the text length plus 16. |
new StringBuffer(CharSequence seq) | Starts with the supplied character sequence. |
Three related concepts must be kept separate:
length()— number of characters currently in the buffer.capacity()— number of characters that can currently fit without growing.ensureCapacity(minimumCapacity)— requests enough capacity to hold at least the specified number of characters.
Expected output
Empty length: 0
Empty capacity: 16
Sized capacity: 50
Seeded length: 14
Seeded capacity: 30
Capacity after ensureCapacity: 100
For the shown standard growth behavior, ensureCapacity(100) makes the capacity at least 100. Capacity is an implementation/storage detail, so code should generally rely on the guarantee of sufficient capacity rather than assume a particular value after arbitrary growth operations.
When should you set an initial capacity?
If you can estimate the final text size, choosing a suitable capacity can reduce buffer expansions. For example, if a report is expected to contain approximately 200,000 characters, creating the buffer with that capacity may avoid repeated growth during construction.
Pre-sizing is an optimization, not a correctness requirement. If the estimate is wrong, the buffer can still grow.
8. Appending Data
append() is the main text-building method. It has overloads for strings, character sequences, individual characters, character arrays, primitive values, and objects.
Expected output
Order: 5021
Customer: Asha
Paid: true
Total: 1499.5
Status: P
Chaining calls
Mutating methods commonly return the same builder object, allowing method chaining:
The calls update one buffer. Chaining improves readability and avoids the need to write a separate statement for every append.
Appending null
When a null reference is passed to an applicable append overload, it is commonly represented as the text null, rather than causing a NullPointerException:
Expected output
Customer: nullThis behavior can be convenient, but it may not be appropriate for user-facing text. If null means “unknown,” choose an explicit fallback such as "Guest" or "Not provided".
9. Inserting, Deleting, Replacing, and Reversing
StringBuffer supports changes at positions other than the end of the text.
insert(offset, value)
Adds content at the specified index. Existing characters at and after that position shift to make room.
delete(start, end)
Removes characters from start inclusive to end exclusive.
deleteCharAt(index)
Removes one character at the specified index.
replace(start, end, str)
Replaces the range from start inclusive to end exclusive with the supplied string. The replacement can be longer or shorter than the removed range.
reverse()
Reverses the character sequence in the buffer.
Expected output
After insert: Java ProgrammingAfter insert: Java
After delete: Java
After replace: Java code
After reverse: edoc avaJ
Index reminder: ranges such as delete(start, end) and replace(start, end, str) use an inclusive start and exclusive end. This convention makes the range length equal to end - start.
Performance note
append() usually avoids shifting existing characters because it writes at the end. An insert() or delete() near the beginning may need to move the characters after the affected position. On a large buffer, repeated front insertions can therefore be more expensive than appending.
10. Reading and Updating Individual Characters
charAt(index) reads a character. setCharAt(index, ch) changes a character already inside the buffer.
Expected output
First character: 0
Updated code: oRD-104
Length: 7
Indexes begin at zero. Calling charAt() or setCharAt() with an index outside the current valid range causes an index-related exception.
setLength(newLength)
setLength() changes the logical length:
- A smaller length truncates the buffer.
- A larger length extends it and fills the newly added positions with the null character
'\u0000'.
Expected output
ABCD
Length: 6
Last character code: 0
Increasing the length this way does not add visible spaces. It adds null characters, which are usually unsuitable for ordinary display text. Use this method carefully.
11. Managing Capacity: ensureCapacity() and trimToSize()
Capacity management controls storage, not the text's logical content.
ensureCapacity(minimumCapacity)ensures that the buffer can hold at least the requested number of characters.trimToSize()asks the implementation to reduce capacity to the current length, removing unused buffer space where possible.- Neither method is a substitute for
setLength(); capacity and length are different.
Expected output
Lenght: 14
Capacity before trim: 100
Capacity after trim: 14
This illustrates the expected effect of trimming in common JDK implementations. Trimming is most relevant when a buffer will be retained for a long time and excess capacity matters. It usually provides little benefit for a short-lived local buffer that is immediately converted to a String.
12. Converting StringBuffer to String
Call toString() when an API requires an immutable String or when the text is ready to be shared as a final result.
Expected output
The returned String is a snapshot of the buffer at the time toString() was called. Later changes to the buffer do not change that String.
StringBuffer does not compare content with equals()
StringBuffer does not override equals() and hashCode() to compare character content. As a result, equals() uses the behavior inherited from Object, which compares object identity.
Expected output
false
true
To compare text content, convert both buffers to strings and compare the resulting strings with String.equals().
13. What Synchronization Guarantees—and What It Does Not
The most important limitation is that thread safety of individual methods does not automatically make a sequence of multiple calls atomic.
For example:
Each append() call is synchronized, but the lock is released between the calls. Another thread may append its own text between them. The result may be a well-formed buffer whose entries are interleaved in an unintended order.
The same issue applies to a sequence such as:
- Read
length(). - Decide what to do based on that value.
- Call
setLength()orappend().
Each method call may be synchronized individually, but another thread can change the buffer between calls.
Make a compound operation atomic
If several operations must be treated as one indivisible action, synchronize the entire group on the same buffer object:
One possible output
[ORDER 1]
[ORDER 2]
[ORDER 3]
[SHIP 1]
[SHIP 2]
[SHIP 3]
Another interleaving of complete lines is possible. The guarantee is that each grouped line is appended while holding the outer lock, so the other thread cannot insert its line in the middle of that group.
Java intrinsic locks are reentrant. When a thread already holds log's monitor and calls a synchronized method on log, it can acquire the same monitor again without deadlocking itself. The monitor is fully released only when the outer synchronized block exits.
Keep synchronized blocks short. Other threads must wait while the monitor is held.
14. Shared Audit Log Example
Consider an e-commerce service where one background thread records order events and another records shipping events. Both threads append to the same audit buffer.
One possible output
[ORDER #1 placed]
[ORDER #2 placed]
[ORDER #3 placed]
[SHIPMENT #1 dispatched]
[SHIPMENT #2 dispatched]
[SHIPMENT #3 dispatched]
Final length: 117
The exact order of order and shipment lines can vary. join() makes the main thread wait until both worker threads finish before printing the final result. The outer synchronized block keeps each multi-call line together. StringBuffer protects each method call internally, while the external block protects the larger logical operation.
For audit systems, synchronization of the buffer alone does not establish business ordering, guarantee durable storage, or replace a proper logging framework. It only addresses access to the shared mutable text buffer.
15. What Can Go Wrong with StringBuilder?
If multiple threads mutate the same StringBuilder without external synchronization, the program has a data race. StringBuilder does not promise thread-safe concurrent mutation.
The expected length is 20,000, but with unsynchronized concurrent writes the actual result is not guaranteed to be correct. The program may appear to work on one run and fail on another. Data races are timing-dependent, so an observed correct output does not prove that the code is safe.
A shared StringBuilder can lose updates or corrupt its internal state. Do not depend on any particular failure mode.
Safe alternatives
Option 1: Use StringBuffer
Its synchronized methods protect individual operations on the shared instance.
Option 2: Keep StringBuilder and synchronize access
This works only if every thread that accesses the shared builder follows the same locking discipline. A single unsynchronized writer can reintroduce the race.
Option 3: Avoid sharing the mutable builder
Give each thread its own StringBuilder, then pass completed immutable strings to a thread-safe queue or combine them after the worker tasks finish. This often scales better because threads do not compete for one buffer lock.
16. Performance Cost of Synchronization
Synchronization has overhead, but the impact depends on the workload and JVM optimizations.
Single-threaded use
When one thread uses a buffer, StringBuffer still uses synchronized methods even though no other thread is competing for the lock. Modern JVMs can optimize many uncontended synchronization operations, so the cost may be small. However, StringBuilder avoids the synchronization contract and is generally the preferred choice for local construction.
Contended use
When many threads repeatedly mutate one shared StringBuffer, they must take turns acquiring the same monitor. This can serialize work and reduce throughput. The shared buffer becomes a contention point.
Benchmark carefully
The exact performance difference depends on hardware, JDK version, warmup, JIT compilation, data sizes, and contention. Avoid presenting a single timing or percentage as a universal guarantee. Use a proper benchmark tool such as JMH for reliable performance comparisons; a simple System.nanoTime() loop is useful for illustration but is not a rigorous benchmark.
A conceptual comparison:
| Workload | Likely choice | Reason |
|---|---|---|
| Local variable used by one thread | StringBuilder | No synchronization is needed. |
| A handful of fixed text pieces | StringBuilder or + | Readability is usually more important than tiny differences. |
| Shared mutable buffer with multiple writers | StringBuffer or explicit locking | Access needs coordination. |
| High-contention shared text accumulation | Redesign if practical | One shared monitor can become a bottleneck. |
Legacy code already using StringBuffer | Keep unless there is a reason to change | Unnecessary refactoring can add risk. |
Older HotSpot JVMs used biased locking, which was deprecated in Java 15 and removed in Java 18. Avoid relying on that historical optimization when making modern performance decisions. Profile the actual application instead of assuming synchronization is always expensive or always free.
17. When to Use StringBuffer, StringBuilder, or String
Use the following decision process:
Comparison table
| Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Mutable content | No | Yes | Yes |
| Individual methods synchronized | Not applicable to mutation; content is immutable | No | Yes |
| Best common use | Final or shared immutable text | Text construction without shared concurrent mutation | Shared mutable text when synchronized method access is appropriate |
| Appending repeatedly | Creates new results when concatenating | Appends into a mutable buffer | Appends into a mutable buffer under synchronization |
equals() compares content | Yes | No | No |
toString() result | Itself is already a String | Returns a String snapshot | Returns a String snapshot |
| Thread-safe for concurrent content changes | Immutable content is safe to share | No, not without external coordination | Individual public calls are synchronized |
| Usual performance for single-thread construction | Not ideal for repeated edits | Usually preferred | Synchronization may add overhead |
Important design nuance
StringBuffer is not automatically the best choice merely because a program uses threads. If each thread has its own local buffer, StringBuilder is still appropriate. The relevant question is whether multiple threads mutate the same instance.
Similarly, StringBuffer does not make a whole workflow atomic. It protects individual public method calls, while a multi-call business operation may need an external synchronized block or a different design.
18. Alternative Designs for Concurrent Text Building
A shared StringBuffer is simple, but it is not always the most scalable architecture.
Per-thread builders
Each thread builds its own text using a local StringBuilder. After the work completes, the results can be combined into a final string. This removes lock contention during construction.
ThreadLocal builders
A ThreadLocal<StringBuilder> can let each thread reuse its own builder across calls. Because each thread accesses its own builder, the buffer is not shared concurrently. Be careful to reset the builder between uses and avoid retaining unexpectedly large buffers in long-lived threads.
Queue completed records
Instead of sharing one mutable string buffer, each thread can create a complete immutable String record and submit it to a thread-safe queue. A single consumer can combine or write the records. This separates record construction from coordination and can make ordering and error handling clearer.
These approaches are design options, not universal replacements. Choose based on required ordering, throughput, memory use, and the responsibilities of the component.
19. Common Pitfalls and How to Avoid Them
Pitfall 1: Assuming synchronized methods make a whole algorithm atomic
A sequence of synchronized calls releases the lock between calls. If a logical operation must not interleave, wrap the full operation in synchronized (buffer) or use a design with a clear single owner.
Pitfall 2: Assuming event order is guaranteed
StringBuffer prevents concurrent method execution on the same instance, but it does not promise that a particular thread always acquires the lock first. Use explicit coordination if order matters.
Pitfall 3: Treating toString() as a live view
toString() returns an immutable snapshot. Later changes to the buffer do not update a previously returned string.
Pitfall 4: Comparing buffers with equals()
Two different StringBuffer objects with the same characters normally compare as unequal using equals(). Convert them to strings before comparing their text.
Pitfall 5: Using StringBuffer everywhere “for safety”
If a builder is local to one method and never shared, synchronization usually adds no useful protection. Prefer StringBuilder for that common case.
Pitfall 6: Sharing StringBuilder without a locking policy
A shared StringBuilder is not thread-safe. If using external synchronization, every read and write that needs protection must follow the same locking protocol.
Pitfall 7: Assuming capacity equals length
A buffer may have spare capacity beyond its current content. Use length() for the number of characters present and capacity() for available storage.
Pitfall 8: Holding the monitor too long
Long synchronized blocks block competing threads. Keep only the operations that must be atomic inside the lock; avoid unrelated I/O or slow computation while holding it.
Pitfall 9: Relying on benchmark results from one run
Tiny differences are easily distorted by JIT warmup, scheduling, and system load. Use repeatable benchmarks and profile the actual workload.
20. Complexity and Performance Notes
Let \(N\) be the number of characters in the resulting text.
| Operation | Typical cost | Notes |
|---|---|---|
length() | \(O(1)\) | Reads the logical character count. |
capacity() | \(O(1)\) | Reads the current capacity. |
charAt(index) | \(O(1)\) | Reads one indexed character. |
setCharAt(index, ch) | \(O(1)\) | Updates one character. |
append(k characters) | Amortized \(O(k)\) | Occasional buffer growth copies existing characters. |
insert(offset, k characters) | Up to \(O(N + k)\) | Existing characters after the insertion point may shift. |
delete(start, end) | Up to \(O(N)\) | Characters after the deleted range may shift. |
replace(start, end, str) | Up to \(O(N + k)\) | Depends on range movement and replacement length. |
reverse() | \(O(N)\) | Visits and rearranges the character sequence. |
toString() | \(O(N)\) | Produces an immutable string containing the current content. |
These are algorithmic expectations, not a promise of exact elapsed time. For synchronized methods, contention can add waiting time that is not captured by the data-structure complexity alone.
21. Practical Best Practices
- Prefer
StringBuilderfor local, single-threaded text construction. - Use
StringBufferwhen multiple threads truly need to mutate the same buffer and synchronized method access is suitable. - Synchronize the complete logical operation when several method calls must stay together.
- Do not rely on
StringBufferto impose a business-event order. - Use
toString()when a stable immutable result is needed. - Compare character content by comparing the results of
toString(), not by callingequals()on two buffers. - Estimate initial capacity for large outputs when a reasonable size estimate is available.
- Avoid repeated front insertions into large buffers when appending and assembling later is possible.
- Keep critical sections short.
- Prefer per-thread buffers and immutable completed results when a shared buffer becomes a bottleneck.
- Benchmark with representative workloads before making performance claims or optimizing.
- Leave stable legacy code alone unless there is a concrete correctness, maintainability, or measured performance reason to change it.
22. Quick Revision Notes
StringBufferis mutable and belongs tojava.lang.- It was introduced in Java 1.0;
StringBuilderarrived in Java 5. - The two classes share buffer-management implementation through
AbstractStringBuilder. StringBuffersynchronizes public methods on the same object.- Synchronization supports mutual exclusion and memory visibility for individual calls.
- A series of individually synchronized calls is not automatically one atomic operation.
append()adds text;insert()adds text at an index;delete()removes a range;replace()substitutes a range;reverse()reverses the sequence.length()counts current characters;capacity()describes current storage capacity.setLength()can truncate content or extend the logical length with null characters.toString()returns an immutable snapshot.StringBuffer.equals()does not compare the character content; compare convertedStringvalues instead.- Use
StringBuilderfor local construction andStringBufferonly when shared mutable access requires its synchronized methods. - For high contention, consider per-thread builders or a queue of completed strings.
23. Conclusion
StringBuffer provides a mutable character buffer with synchronized public methods. Its API closely matches StringBuilder, but the synchronization changes how concurrent access is handled. Individual operations on a shared instance are protected by the object's monitor, helping preserve the buffer's internal consistency and making writes visible across synchronized access.
That guarantee has boundaries: multiple method calls do not automatically form one atomic operation, thread scheduling does not establish a desired business order, and a shared monitor can become a performance bottleneck. For ordinary single-threaded text construction, StringBuilder remains the preferred default. Use StringBuffer when shared mutable access is genuinely required, and consider designs that avoid sharing a mutable buffer when throughput or ordering requirements become more demanding.