Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

StringBuffer  RSS feed

 
Prabjhot Singh
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

private static StringBuffer temp = new StringBuffer();

temp can't be appended simultaneously by multiple threads, but multiple threads can append it before it's returned to client(s).
Am I correct?
 
Junilu Lacar
Sheriff
Posts: 11172
160
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That sounds about right. StringBuffer is thread-safe, therefore only one thread at a time can actually mutate it. There can be multiple threads attempting to mutate it at the same time but other threads need to wait for their turn before they can mutate the StringBuffer.
 
Campbell Ritchie
Marshal
Posts: 55799
164
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But why do you want to allow multiple threads anywhere near it? Use a StringBuilder instead and make it a local variable, so only one thread can access it. Don't return the StringBuilder but myStringBuilder.toString() and change the return type to String. Strings are implicitly thread‑safe because they are immutable.
 
Prabjhot Singh
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Junilu & Campbell for your reply... its helpful...

as suggested, I have stopped using StringBuffer & using StringBuilder, and have used in local methods with return as sb.toString() in the past..

it's done by someone else.... thanks...
 
Junilu Lacar
Sheriff
Posts: 11172
160
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prabjhot Singh wrote:
as suggested, I have stopped using StringBuffer & using StringBuilder, and have used in local methods with return as sb.toString() in the past..
it's done by someone else.... thanks...

By that, I hope you mean the same thing as what Campbell was suggesting: use a local variable instead of a static member variable.

Just so we're all on the same page:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!