Java Reference
In-Depth Information
10-3. Inserting a Key into a Map Only if
the Key Is not Already Present
Problem
A Map within your application is continuously being updated, and you need to put a
key/value pair into it if the key does not already exist. Therefore, you need to check for
the key's presence, and you need assurance that some other thread doesn't insert the
same key in the meantime.
Solution
Using the ConcurrentMap.putIfAbsent() method, you can determine whether
the map was modified atomically. For example, the following code uses the method to
check and insert in a single step, thus avoiding the concurrency problem:
private void start() {
ConcurrentMap<Integer, String> concurrentMap = new
ConcurrentHashMap<>();
for (int i = 0; i < 100; 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());
});
}
Search WWH ::




Custom Search