Why is List not thread-safe?

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.

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);
}

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.

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.

.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”

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

Reference Vector thread safety: http://www.ibm.com/developerworks/java/library/j-jtp09263.html

Leave a Comment