1

StringBuffer class having methods which are thread safe? OK but i have question that when the particular method will be called then it will be loaded on to stack and stack is thread safe so why we need the thread safe method?

4

1 回答 1

3

It's quite possible to share a given StringBuffer instance across different threads in which case multiple threads will end up "modifying" or mutating the StringBuffer's internal state. This is why it's required to explicitly synchronize append methods on a StringBuffer.

But you are right. If you don't plan on sharing stuff across thread boundaries (or like they call "publish" the instance), it is more logical to just create a StringBuilder instance (which is the non-synchronized brother of StringBuffer) in a given method call and throw it away (or more like let the GC take care of it) after the method call ends.

There is another aspect which comes into play when you absolutely have to share instances across threads and at the same time feel that the cost of synchronizing each operation is way too much -- thread locals. Basically, the idea in this case is to make each thread have its own copy of a "mutable" entity. There is no locking required because the moment some other thread tries to access a thread local variable, you hand across a fresh/pre-configured instance. This is commonly used for stuff like sharing StringBuilder and DateFormat instances to boost performance.

If you want to compare between raw/unsafe sharing of a mutable object between threads versus using a thread local, take a look at the snippet I have hosted on Bitbucket.

于 2012-11-03T07:51:06.060 回答