• Post Reply Bookmark Topic Watch Topic
  • New Topic

StringBuffer and StringBuilder  RSS feed

 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
" In terms of methods supported by the classes, the methods of StringBuffer and StringBuilder are identical. They only differ in whether the methods are synchronized or not. " - Oracle Certified Associate Java SE7 Programmer Study Guide


What does synchronized mean in this context?
 
Ranch Hand
Posts: 411
5
IntelliJ IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
synchronized in this context simply mean that the methods in the StringBuffer class is thread-safe. The code in this class can be accessed by only one thread at a time on an instance of this class, which qualifies it to be used safely in multi-threaded applications. On the other hand, the StringBuilder class is not a thread-safe class because its methods aren't synchronized thus making it a bad choice for use in multi-threaded applications.
 
Marshal
Posts: 56606
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But you usually use builders as local variables in methods, so thread safety is not an issue.
 
Rico Felix
Ranch Hand
Posts: 411
5
IntelliJ IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:But you usually use builders as local variables in methods, so thread safety is not an issue.


In the event that you do use one for some reason as a field in a class, then thread safety will become an issue, therefore knowing the subtle differences will help
 
Miles Williams
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks folks.
Much appreciated.
I won't be needing to worry about this kind of thing for a while I think as I am not at the stage where I am familiar with concurrency.
 
Campbell Ritchie
Marshal
Posts: 56606
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
One thing always worth remembering about concurrency, even if you aren't using it yet: mark your classes as being not thread‑safe, then you know you will have to take precautions. That doesn't apply to immutable classes which are implicitly thread‑safe.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!