Java Reference
In-Depth Information
Problem
You need to update a Map object from multiple threads, and you want to make sure that
the update doesn't break the contents of the Map object and that the Map object is al-
ways in a consistent state. You also want to traverse (look at) the content of the Map
object while other threads are updating the Map object.
Solution
Use a ConcurrentMap to update Map entries. The following example creates 1,000
threads. Each thread then tries to modify the Map at the same time. The main thread
waits for a second, and then proceeds to iterate through the Map (even when the other
threads are still modifying the Map ):
Set<Thread> updateThreads = new HashSet<>();
private void start() {
ConcurrentMap<Integer,String> concurrentMap = new
ConcurrentHashMap<>();
for (int i =0;i < 1000;i++) {
startUpdateThread(i, concurrentMap);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
concurrentMap.entrySet().stream().forEach((entry) -> {
System.out.println("Key :"+entry.getKey()+"
Value:"+entry.getValue());
});
updateThreads.stream().forEach((thread) -> {
thread.interrupt();
});
}
Search WWH ::




Custom Search