File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/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


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
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: 14337
    
  22

That depends on what you do with the StringBuffer.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
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: 39755
    
  28
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: 61
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