简体   繁体   English

为什么添加了非线程安全的java类?

[英]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. 我看到很多类被添加到Java中,这些类不是线程安全的。

Like StringBuilder is not thread safe while StringBuffer was and StringBuilder is recoomended over Stringbuffer. 像StringBuffer一样,StringBuilder不是线程安全的,StringBuilder是通过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 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 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. StringBuffer就是其中之一恕我直言。

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. 很难找到一个人为的例子,说明何时以多线程方式使用StringBuffer,这种方式无法通过其他方式实现。

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. 也就是说,为什么还有一些类添加到Java库中,这些类不是线程安全的。

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() ). “使每个方法同步”策略只能提供关于一个对象的一致性的保证,并且它有可能引入死锁,或者比想象的要弱(想想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: StringBuilder的典型用法是:

return new StringBuilder().append("this").append("that").toString()

all in one thread, no need to synchronize anything. 所有在一个线程中,不需要同步任何东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM