From the course: Advanced Java: Threads and Concurrency
Unlock the full course today
Join today to access over 24,300 courses taught by industry experts.
Using concurrent collections - Java Tutorial
From the course: Advanced Java: Threads and Concurrency
Using concurrent collections
- [Instructor] First, I'm showing you how a regular hash map, which we know isn't thread safe, handles reads and modifications by multiple threads. Four items are loaded into the productMap in the construct. In the iterateMap method in line 14, a thread iterates through the elements of the map and prints them out. In the modifyMap method in line 26, another thread modifies the same map by removing the element with a key of 102 from it. Both the methods are called in the main method. Let's run it. You can see that thread one is kicked off and it prints the list of products in the map. While that happens, thread two tries to modify the map and remove product 102. That's when it encounters the annoying concurrent modification exception. But fortunately, there's the concurrent hashMap, which is the concurrent version of the hashMap. Before I show you how to solve our problem using it, let's see how it does that. It internally maintains a hash table that's divided into segments or…