Junior — Middle
How to ensure thread safety when using StringBuilder in a multithreaded environment?
sobes.tech AI
Answer from AI
StringBuilder in Java is not thread-safe because its methods are not synchronized. To ensure thread safety when using StringBuilder in a multithreaded environment, you can:
- Use an external synchronization mechanism, such as synchronized blocks:
StringBuilder sb = new StringBuilder();
synchronized(sb) {
sb.append("text");
}
-
Use the StringBuffer class, which is a thread-safe counterpart of StringBuilder, as its methods are synchronized.
-
If high performance and minimal locking are required, you can use local instances of StringBuilder in each thread or other approaches, such as thread-safe queues for accumulating data.
Most often, StringBuilder is simply replaced with StringBuffer for thread safety.