Is .NET’s StringBuilder thread-safe

Absolutely not; here’s a simple example lifted from 4.0 via reflector: [SecuritySafeCritical] public StringBuilder Append(char value) { if (this.m_ChunkLength < this.m_ChunkChars.Length) { this.m_ChunkChars[this.m_ChunkLength++] = value; } else { this.Append(value, 1); } return this; } The attribute just handles callers, not thread-safety; this is absolutely not thread-safe. Update: looking at the source he references, this is … Read more

How do I prove programmatically that StringBuilder is not threadsafe?

Problem I am afraid the test you have written is incorrect. The main requirement is to share the same StringBuilder instance between different threads. Whereas you are creating a StringBuilder object for each thread. The problem is that a new Threadsafe() initialises a new StringBuilder(): class Threadsafe { … StringBuilder sb = new StringBuilder(str); … … Read more

Remove last character of a StringBuilder?

Others have pointed out the deleteCharAt method, but here’s another alternative approach: String prefix = “”; for (String serverId : serverIds) { sb.append(prefix); prefix = “,”; sb.append(serverId); } Alternatively, use the Joiner class from Guava 🙂 As of Java 8, StringJoiner is part of the standard JRE.

How can I clear or empty a StringBuilder? [duplicate]

Two ways that work: Use stringBuilderObj.setLength(0). Allocate a new one with new StringBuilder() instead of clearing the buffer. Note that for performance-critical code paths, this approach can be significantly slower than the setLength-based approach (since a new object with a new buffer needs to be allocated, the old object becomes eligible for GC etc).