Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java StringBuilder and Thread Safety

I am building up a String out of multiple pieces and want to use either StringBuffer or StringBuilder to do so. From the Java 5 docs, I see that StringBuilder is preferred when possible, with the caveat that

Instances of StringBuilder are not safe for use by multiple threads.

From this statement, I understand that I should not have a single StringBuilder instance shared by multiple threads. But what about this case:

//Is this safe?
//foo() is called simultaneously by multiple threads
String foo(String a, String b) {
    return new StringBuilder(a).append(b).toString();
}

Here there could be multiple threads in the function at the same time, using the StringBuilder class at the same time (eg, concurrent access of static variables, if there are any), but each thread would have its own separate instance of StringBuilder. From the documentation, I can not quite decide whether this counts as use by multiple threads or not.

like image 633
Ben Avatar asked Mar 10 '09 18:03

Ben


People also ask

How is StringBuilder not thread safe?

StringBuilder is not synchronized so that it is not thread-safe. By not being synchronized, the performance of StringBuilder can be better than StringBuffer. If we are working in a single-threaded environment, using StringBuilder instead of StringBuffer may result in increased performance.

Which of the following are thread safe StringBuffer or StringBuilder?

String is immutable whereas StringBuffer and StringBuilder are mutable classes. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That's why StringBuilder is faster than StringBuffer.

Is StringBuffer thread safe example?

StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously. StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.

Is thread safe in Java?

Since String is immutable in Java, it's inherently thread-safe. 2) Read-only or final variables in Java are also thread-safe in Java. 3) Locking is one way of achieving thread-safety in Java. 4) Static variables if not synchronized properly become a major cause of thread-safety issues.


2 Answers

That's perfectly fine. Local variables have no problems with thread safety as long as they don't access or mutate instance or class variables.

like image 161
Michael Myers Avatar answered Sep 19 '22 06:09

Michael Myers


Yes, that is safe, because the StringBuilder object is used only locally (each thread calling foo() will generate its own StringBuilder).

You should also note that the code you posted is practically identical to the bytecode generated by this:

String foo(String a, String b) {
    return a + b;
}
like image 43
Kip Avatar answered Sep 21 '22 06:09

Kip