7

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?

Bob Roberts
  • 539
  • 8
  • 22
  • possible duplicate of [StringBuilder and StringBuffer in Java](http://stackoverflow.com/questions/355089/stringbuilder-and-stringbuffer-in-java) – kosa Aug 23 '12 at 20:06
  • @thinksteep This question is suppose to focus on what sort of threading happens behind the scenes in webapps and how that affects String building. – Bob Roberts Aug 23 '12 at 20:08
  • 4
    Probably not a duplicate. This seems to be more of a question about threading in Tomcat than the StringBuilder/StringBuffer classes themselves. – Mike M Aug 23 '12 at 20:08

5 Answers5

11

If you are using a local variable you can safely use StringBuilder. Each thread will get its own instance.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 4
    +1. And if you *are* sharing strings between threads (e.g. by using static fields), then you should probably be using `String` rather than either `StringBuilder` *or* `StringBuffer`. – ruakh Aug 23 '12 at 20:09
  • 4
    To emphasize ruakh's point: passing immutable data between threads is the safe approach. – Mike M Aug 23 '12 at 20:11
2

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.

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
Razvan
  • 9,925
  • 6
  • 38
  • 51
1

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.

safeghost
  • 11
  • 1
1

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.

Sam
  • 554
  • 1
  • 12
  • 23
0

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.

Mike Barlotta
  • 715
  • 4
  • 16