Java Reference
In-Depth Information
SYNCHRONIZED COLLECTION CLASSES
If you've ever wondered why the Vector and Hashtable (and related) classes are synchronized,
here's a bit of history.
In the very early days of Java, these were the only collection classes in the JDK. Back then (be-
fore Java 1.2), there was no formal definition of the Collections Framework; these were just use-
ful classes that the original Java platform provided.
When Java was first released, threading was poorly understood by most developers, and Java at-
tempted to make it easier for developers to avoid some of the pitfalls of coding in a threaded en-
vironment. Hence, these classes were thread-safe.
Unfortunately, synchronization—even uncontended synchronization—was a huge performance
problem in early versions of Java, so when the first major revision to the platform came out, the
Collections Framework took the opposite approach: all new collection classes would be unsyn-
chronized by default. Even though synchronization performance has drastically improved since
then, it still is not free, and having the option of unsynchronized collections helps everyone to
write faster programs (with the occasional bug caused by concurrently modifying an unsynchron-
ized collection).
Chapter 9 posited a microbenchmark to compare CAS-based protection to traditional syn-
chronization. That proved to be impractical in the threaded case, but what if the data in ques-
tion will only ever be accessed by a single thread—what would be the effect of not using any
synchronization at all? Table 12-7 shows that comparison. Because there is no attempt to
model the contention, the microbenchmark in this case is valid in this one circumstance:
when there can be no contention, and the question at hand is what the penalty is for “over-
synchronizing” access to the resource.
Table 12-7. Performance of synchronized and unsynchronized access
Mode
Total time
Per-operation time
CAS operation
6.6 seconds 13 nanoseconds
Synchronized method
11.8 seconds 23 nanoseconds
Unsynchronized method 3.9 seconds 7.8 nanoseconds
Search WWH ::




Custom Search