This content has been marked as final. Show 3 replies
user10739046 wrote:you actually have code which depends on the thread-safe behavior of StringBuffer? you have multiple threads trying to simultaneously append the same StringBuffer instance?
The fact they don't makes swapping them out a bit of a pain if you have a utility class that uses them where you actually need the threadsafe behavior of StringBuffer sometimes.
I think your over complicating your life by trying to use a common interface or similar gimmick. I don't even think its a good idea to put StringBuilder/StringBuffer in a utility class. I suggest instead you use StringBuilder directly everywhere unless you specifically have a situation that justifies StringBuffer. This way, the code maintainer that comes after you will not go nuts trying to decide which is a thread issue and which isn't. Additionally, you might want to put a comment above each use of StringBuffer saying why you are using it instead of StirngBuilder. This way, the code maintainer realizes you have a justification for using it and didn't accidently use it instead of StringBuilder.
I don't know what your actual requirements are for having a StringBu***er shared by more than one thread, but just synchronizing all the methods of an object doesn't always provide adequate thread-safety. For example it's possible that you may want to do something like
in an atomic way (i.e. "foo" comes immediately before that bar-value with nothing in between), in which case relying on the fact that the append() method of StringBuffer is synchronized isn't good enough.
In other words since you have to consider thread-safety issues like this, perhaps you might as well just use StringBuilder throughout. This would force you to consider thread-safety properly, instead of being lulled into complacency by the faux thread-safety provided by StringBuffer.