Why Classes to java have been added which are not thread safe?
I am seeing a lot of classes being added to Java which are not thread safe.
Like StringBuilder is not thread safe while StringBuffer was and StringBuilder is recoomended over Stringbuffer.
Also various collection classes are not thread safe.
Isn't being thread safe a good thing ?
Or i am just stupid and don't yet understand the meaning of being开发者_运维技巧 thread safe ?
Because thread safety makes things slower, and not everything has to be multi-threaded.
Consider reading this article to find out basics about thread safety :
http://en.wikipedia.org/wiki/Thread_safety
When you comfortable enough with the threads/or not, consider reading this book, it has great reviews :
http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601
Some classes are not suitable for using across multiple threads. StringBuffer is one of them IMHO.
It is very hard to find even a contrived example of when you would use StringBuffer in a multi-threaded way that cannot be more simple achieve other ways.
Thread safety is not a all or nothing property. Ten years ago some books recommended marking all methods of a class as synchronized in order to make them thread safe. This costs some performane, but it is far from a guarantee that your overall program is thread safe. Therefore, you have costs with a questionable gain. That is, why there are still classes added to Java library which are not thread safe.
The "make every method synchronized" strategy is only able to provide guarantees about the consistency of one object, and it has the potential to introduce dead-locks, or to be weaker than thought (think about wait()
).
There is a performance overhead to inherently thread-safe code. If you do not need the class in a concurrent context but need the performance to be high then these, original classes are not ideal.
A typical usage of StringBuilder is something like:
return new StringBuilder().append("this").append("that").toString()
all in one thread, no need to synchronize anything.
精彩评论