What does " StringBuilders are not thread-safe" mean?

Elyas Hadizadeh picture Elyas Hadizadeh · Nov 11, 2014 · Viewed 11.8k times · Source

I have read some articles about the pros and cons of String and StringBuilder in the Java Programming language. In one of the articles, the author mentioned that:

StringBuilder is not Thread-safe, so in multiple threads use StringBuffer.

Unfortunately, I cannot understand what it means. Could you please explain the difference between String, StringBuilder and StringBuffer especially in the context of "Thread safety".

I would appreciate it if you could describe with the code example.

Answer

Eran picture Eran · Nov 11, 2014

If multiple threads are modifying the same instance of a StringBuilder, the result can be unexpected - i.e. some of the modifications may be lost. That's why you should use StringBuffer in such situations. If, however, each thread StringBuilder instance can be modified by only one thread, it is better to use StringBuilder, since it would be more efficient (thread safety comes with a performance cost).