Skip to Content
Course content

273: The StringBuilder and StringBuffer Compared

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I want to show you a piece of code that looks perfectly fine at first glance. Imagine you're building a system that collects logs from several different threads—maybe different parts of a web server handling requests—and you're appending them to a single shared buffer to write to a file later.

public class LogCollector {
    private StringBuilder sharedLog = new StringBuilder();

    public void addLog(String message) {
        sharedLog.append(message).append("\n");
    }

    public String getFullLog() {
        return sharedLog.toString();
    }
}

// Usage in a multi-threaded environment
// Thread 1: collector.addLog("User A logged in");
// Thread 2: collector.addLog("User B clicked Home");
// Thread 3: collector.addLog("Database connection lost!");

The Mystery of the ArrayIndexOutOfBoundsException

If you run this in a single-threaded test, it works flawlessly. But once you deploy this to a production environment with actual concurrency, you're going to see something strange. Your logs will occasionally be missing characters, or worse, your application will crash with an ArrayIndexOutOfBoundsException coming from inside the StringBuilder.append() method.

Here is what's happening: StringBuilder is not thread-safe. It manages an internal character array. When that array fills up, StringBuilder allocates a larger array and copies the old data over. If two threads call append() at the exact same millisecond, they might both see that there is one slot left in the array. They both try to write to that same slot, or one tries to write while the other is in the middle of resizing the array. It's a classic race condition.

ReplacingStringBuilder with StringBuffer

In most of your daily work, StringBuilder is the right choice because it's faster. But in this specific case, we need synchronization. This is where StringBuffer comes in. To fix this, we simply swap the implementation:

public class LogCollector {
    // Changed StringBuilder to StringBuffer
    private StringBuffer sharedLog = new StringBuffer();

    public void addLog(String message) {
        sharedLog.append(message).append("\n");
    }

    public String getFullLog() {
        return sharedLog.toString();
    }
}

Why does this fix the crash? Because StringBuffer is essentially a "synchronized" version of StringBuilder. Almost every one of its public methods is marked with the synchronized keyword. This ensures that only one thread can modify the internal character array at a time. The race condition vanishes, and your logs remain intact.

Choosing Between Performance and Safety

You might be wondering, "If StringBuffer is safer, why would I ever use StringBuilder?" It comes down to overhead. Acquiring and releasing a lock (synchronization) takes a small amount of time. In a tight loop that runs a million times, that overhead adds up.

I follow a simple rule of thumb:

  • Use StringBuilder for 95% of your tasks. If the variable is local to a method, it's physically impossible for other threads to access it, so synchronization is a waste of CPU cycles.
  • Use StringBuffer only when you have a shared, mutable string buffer that is explicitly accessed by multiple threads simultaneously.

Keep in mind that in modern Java architecture, we usually avoid sharing mutable state like this anyway (preferring thread-safe queues or logging frameworks), but understanding the difference between these two classes is vital for reading legacy code and knowing how Java handles concurrency under the hood.




📋 Practical Task

Build a Concurrent Transaction Journal

You are tasked with creating a TransactionJournal class that allows multiple simulated banking threads to record transactions into a single shared string.

Requirements:

  • Create a class TransactionJournal with a method recordTransaction(String txId, double amount).
  • The journal must use a thread-safe buffer to ensure that when multiple threads record transactions simultaneously, no data is lost and no exceptions are thrown.
  • Implement a main method that spawns 10 different threads. Each thread should record 100 transactions (1,000 total) into the shared journal.
  • After all threads have finished (use join()), print the total length of the final string to verify that all 1,000 entries were recorded successfully.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.