aspose file tools*
The moose likes Java in General and the fly likes stringBuffer in java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "stringBuffer in java" Watch "stringBuffer in java" New topic
Author

stringBuffer in java

priyanaka jaiswal
Ranch Hand

Joined: Jun 03, 2011
Posts: 79
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

Joined: Aug 16, 2005
Posts: 13875
    
  10

That depends on what you do with the StringBuffer.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
priyanaka jaiswal
Ranch Hand

Joined: Jun 03, 2011
Posts: 79
Hi Jesper

Can you give one example where we need to synchronize the stringBuffer?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36514
    
  16
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

Joined: Apr 19, 2013
Posts: 60
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.


science belief, great bioscience!
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

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
 
subject: stringBuffer in java
 
Similar Threads
StringBuffer Class
Copy of value and reference
Synchronized Code Behavior
byte [ ] to StringBuffer
String and StringBuffer