Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
If multiple threads concurrently modify a data structure such as a hash table, then it is easily possible to damage the data structure. (See Chapter 13 for more information on hash tables.) For example, one thread may begin to insert a new element. Suppose it is preempted while it is in the middle of rerouting the links between the hash table’s buckets. If another thread starts traversing the same list, it may follow invalid links and create havoc, perhaps throwing exceptions or being trapped in an infinite loop.
You can protect a shared data structure by supplying a lock, but it is usually easier to choose a thread-safe implementation instead. The blocking queues that we discussed in the preceding section are, of course, thread-safe collections. In the following sections, we discuss the other thread-safe collections that the Java library provides.