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.
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.
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.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With