且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么名单< T>不是线程安全的?

更新时间:2022-05-15 15:31:40

您真的需要进行分类Java的Vector的类型线程安全的。 Java类Vector是安全,可以从多个线程使用,因为它使用的方法同步。国家将不会被破坏。

You really need to classify Java's Vector's type of thread safety. Javas Vector is safe to be used from multiple threads because it uses synchronization on the methods. State will not be corrupted.

不过,Java的载体的有用性从多个线程无需额外的同步限制。例如,考虑从一个vector

However, Java's vector's usefulness is limited from multiple threads without additional synchronization. For example, consider the simple act of reading an element from a vector

Vector vector = getVector();
if ( vector.size() > 0 ) { 
  object first = vector.get(0);
}

这个方法不会破坏载体的状态,但它也是不正确的。尽管没有理由变异的载体中,如果语句中的get()调用之间停止另一个线程。这code能和终因竞争状态失败。

This method will not corrupt the state of the vector, but it also is not correct. There is nothing stopping another thread from mutating the vector in between the if statement an the get() call. This code can and will eventually fail because of a race condition.

这类型的同步仅在场景一福有用的,这肯定是不便宜。你付出了noticable价格同步,即使你不使用多个线程。

This type of synchronization is only useful in a handfull of scenarios and it is certainly not cheap. You pay a noticable price for synchronization even if you don't use multiple threads.

净选择不支付这样的价格在默认情况下只用处不大的情况下。相反,它选择实施锁空闲列表。作者负责添加任何同步。这是更接近C ++的模式只支付您所使用的

.Net chose not to pay this price by default for a scenario of only limited usefulness. Instead it chose to implement a lock free List. Authors are responsible for adding any synchronization. It's closer to C++'s model of "pay only for what you use"

我最近写了几篇文章上使用集合,只有内部同步,如Java的矢量的危险。

I recently wrote a couple of articles on the dangers of using collections with only internal synchronization such as Java's vector.

  • Why are thread safe collections so hard?
  • A more usable API for a mutable thread safe collection

参考向量线程安全: http://www.ibm.com /developerworks/java/library/j-jtp09263.html