• Post Reply Bookmark Topic Watch Topic
  • New Topic

StringBuffer  RSS feed

 
Mohammad Nabeeluddin Ansari
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I dont see any reason in creating a method local StringBuffer variable as method local variables will be created for each and every thread.

Is there any scenario in which it is required to create StringBuffer as method local(think of it in a multithreaded environment).

Regards:
Nabeel
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, unless you need the synchronization use a StringBuilder instead of a StringBuffer.

In at least 99.999% of the cases you really want each thread to have its own StringBuilder. If you would share the same StringBuilder, anything you add to it from one thread becomes visible in all the other threads as well. And that's usually not what you want.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mohammad Nabeeluddin Ansari wrote:
Is there any scenario in which it is required to create StringBuffer as method local(think of it in a multithreaded environment).

from Rob sentence:

anything you add to it from one thread becomes visible in all the other threads as well.

for above quote you can use StringBuffer. think about below scenario,

but again, most of the time StringBuffer not required to declare as method local variable. use StringBuilder instead!
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well, when you really need to share it like in that example, StringBuffer all of a sudden has an advantage over StringBuilder - built-in synchronization.
 
john sal
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the creation and the desctrution of an object is done within the same method then use StringBuilder however if object escapes the boundary of the the method means you are passing or storing it elsewhere then it StringBuffer should be used instead.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!