Java Reference
In-Depth Information
Random random = new Random();
private void startUpdateThread(int i, final
ConcurrentMap<Integer, String> concurrentMap) {
Thread thread = new Thread(() -> {
while (!Thread.interrupted()) {
int randomInt = random.nextInt(20);
concurrentMap.put(randomInt,
UUID.randomUUID().toString());
}
});
thread.setName("Update Thread "+i);
updateThreads.add(thread);
thread.start();
}
How It Works
For performing work on a
HashTable
in a concurrent manner,
Concur-
rentHashMap
allows multiple threads to modify the
HashTable
concurrently and
safely.
ConcurrentHashMap
is a
HashTable
supporting full concurrency for re-
trievals, and high concurrency for updates. In the example, 1,000 threads make modi-
fications to the
Map
over a short period of time. The
ConcurrentHashMap
iterator,
as well as streams that are generated on a
ConcurrentHashMap
, allows safe itera-
tion over its contents. When using the
ConcurrentMap
's iterator, you do not have to
worry about locking the contents of the
ConcurrentMap
while iterating over it (and
it doesn't throw
ConcurrentModificationExceptions
).
For a complete list of the newly added methods, refer to the online documentation
Note
ConcurrentMap
iterators, while thread-safe, don't guarantee that you will
see entries added/updated after the iterator was created.