Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use StringBuilder or StringBuffer for webapps?

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?

like image 767
Bob Roberts Avatar asked Aug 23 '12 20:08

Bob Roberts


2 Answers

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

like image 97
Mark Byers Avatar answered Sep 23 '22 09:09

Mark Byers


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.

like image 26
Razvan Avatar answered Sep 26 '22 09:09

Razvan