This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

stringBuffer in java

 
priyanaka jaiswal
Ranch Hand
Posts: 79
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,


Is any necessity to synchronize the StringBuffer as it is mutable even though it is thread safe in mutithreaded environment?


Thanks in advance
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That depends on what you do with the StringBuffer.
 
priyanaka jaiswal
Ranch Hand
Posts: 79
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jesper

Can you give one example where we need to synchronize the stringBuffer?
 
Campbell Ritchie
Sheriff
Pie
Posts: 47270
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please look at this thread. There are example of how a supposedly thread‑safe object can behave as if thread‑unsafe.
 
drac yang
Ranch Hand
Posts: 62
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
from the above thread, does it mean that because the granularity of the synchronization of StringBuffer is only method, so it would not be safe when it comes to uses of inter-methods.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
drac yang wrote:from the above thread, does it mean that because the granularity of the synchronization of StringBuffer is only method, so it would not be safe when it comes to uses of inter-methods.


Correct. And the same is true of any "synchronized class" (which isn't actually a thing, but which is what people sometimes call a class whose public methods are all synchronized). Using only synchronization, there's no way for a class to ensure exclusivity or atomicity across multiple method calls.

It is possible to do something like that using the facilities in java.util.concurrent, but I wouldn't advise it in general, and I'm not aware of any classes that do it.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic