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.

1
Subscribe to my newsletter

Read articles from Sudarshan Doiphode directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sudarshan Doiphode
Sudarshan Doiphode

๐Ÿ‘‹ Hey there! I'm Sudarshan, a tech enthusiast with a focus on: โ€ข ๐Ÿš€ Spring Boot โ€ข ๐ŸŒผ Spring โ€ข ๐Ÿ”’ Spring Security โ€ข ๐ŸŒฑ Hibernate โ€ข โ˜• Java 8 & Java โ€ข ๐Ÿš€ Apache Kafka โ€ข ๐Ÿ›ข๏ธ Apache Maven โ€ข ๐Ÿณ Docker โ€ข ๐Ÿ”— Git โ€ข ๐Ÿ—๏ธ Design Patterns โ€ข And more tech adventures! Follow for insights and join the journey. ๐ŸŒŸ๐Ÿ‘จโ€๐Ÿ’ป #TechEnthusiast