Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 775
Lokesh Sah Avatar asked Nov 30 '22 04:11

Lokesh Sah


2 Answers

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

like image 161
ant Avatar answered Dec 15 '22 03:12

ant


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.

like image 33
Peter Lawrey Avatar answered Dec 15 '22 03:12

Peter Lawrey