What do you mean by StringBuilder is not a thread safe ?

What do you mean by StringBuilder is not a thread safe ?

Hello Developers 🧑‍💻, I have been asking this question in interviews most of the time, and I get disappointed by candidates.

Everyone knows StringBuilder helps in creating mutable string objects because a normal String object is immutable. But when it comes to answering more about StringBuilder, the candidate just says StringBuilder is non-synchronized. However, when I ask them to give a simple example proving that StringBuilder is non-synchronized, they lack practical understanding.

Why is StringBuilder Non-Synchronized?

The non-synchronized nature of StringBuilder is by design, to improve performance in single-threaded environments. Synchronization introduces overhead, and in scenarios where thread safety is not a concern, StringBuilder offers a more efficient option for string manipulation.

Practical Example: The Race Condition

Here's a code example demonstrating a potential issue if you use StringBuilder in a multithreaded environment without proper synchronization:

  1. We create a StringBuilder object sb.

  2. Three threads are created:

    • t1 appends "A" to sb 1000 times.

    • t2 appends "B" to sb 1000 times.

  3. Both threads start executing concurrently.

  4. Since StringBuilder is non-synchronized, there's no guarantee about the order in which characters are appended. In a perfect scenario, the final string would be "AAABBBBAAAABBBBAAA..." (2,000 characters alternating A and B).

  5. However, due to the race condition, the order might be interleaved, resulting in an unexpected output like "ABABABABABABABABABAB...".

Key Takeaways:

  • StringBuilder is ideal for efficient string manipulation in single-threaded environments.

  • Its non-synchronized nature makes it unsuitable for multithreaded scenarios without proper synchronization mechanisms (like synchronized blocks or concurrent collections).

  • For thread safety in multithreaded environments, consider using StringBuffer (though it's slightly less performant).

Conclusion

When StringBuilder is used in a multi-threaded environment without proper synchronization, it can lead to incorrect results. If thread safety is a concern, consider using StringBuffer or synchronizing the access to the StringBuilder instance externally.