Reputation: 559
I a writing a webapp in Java 1.6 and running it in tomcat. While I am not doing any explicit threading, I wonder about what is going on behind the scenes with Spring and Tomcat. Would I run into any issues using StringBuilder instead of StringBuffer?
Upvotes: 8
Views: 3023
Reputation: 564
The Java doc says regarding java.lang.StringBuffer:
Whenever an operation occurs involving a source sequence (such as appending or inserting from a source sequence) this class synchronizes only on the string buffer performing the operation, not on the source.
This means your operations on your StringBuffer will be safe even if you are in multi-thread environment [like web app]. The safety of your StringBuffer instance as such is governed by the scope of the variable.
Upvotes: 1
Reputation: 21
Use StringBuilder since your builder is a local variable in doPost or doGet or else. It's true that multiple server threads use the same servlet instance but the fact that your builder is a local variable, there is no reason to worry ! If your builder was a member of your servlet class, sure you would get thread-safety problems. It's not your case i guess.
Upvotes: 2
Reputation: 10093
Usually Java EE components are not thread-safe by default, so unless you synchronize the blocks of code where you use the StringBuilder
, you'll experience race-conditions. So, you either have to take care of synchronization or use StringBuffer
.
Of course, as already mentioned if the StringBuilder
is a local variable, you don't have to worry about that.
Upvotes: 2
Reputation: 725
if the code is in a Servlet (doGet/doPost) then multiple requests will cause the servlet instance to be multi-threaded. If the code is in a Spring bean it will depend on whether you configured the bean to be a singleton or prototype.
Upvotes: 0
Reputation: 838266
If you are using a local variable you can safely use StringBuilder
. Each thread will get its own instance.
Upvotes: 12