ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

ConcurrentHashMap Entry Removal Logic

Java

Goal -- WPM

Ready
Exercise Algorithm Area
1import java.util.concurrent.ConcurrentHashMap;
2import java.util.function.Predicate;
3
4public class CustomConcurrentMap {
5
6private ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
7
8public void removeEntriesIf(Predicate<Integer> condition) {
9map.forEach((key, value) -> {
10if (condition.test(value)) {
11map.remove(key, value); // Atomic removal if value matches
12}
13});
14}
15
16public static void main(String[] args) {
17CustomConcurrentMap customMap = new CustomConcurrentMap();
18customMap.map.put("A", 1);
19customMap.map.put("B", 2);
20customMap.map.put("C", 3);
21customMap.map.put("D", 4);
22
23customMap.removeEntriesIf(value -> value % 2 == 0);
24System.out.println(customMap.map);
25}
26}
Algorithm description viewbox

ConcurrentHashMap Entry Removal Logic

Algorithm description:

This example demonstrates how to implement a conditional removal operation on a `ConcurrentHashMap`. The `removeEntriesIf` method iterates through the map and removes entries whose values satisfy a given predicate. It leverages the `ConcurrentHashMap`'s atomic `remove(key, value)` operation to ensure thread safety during removal, preventing race conditions where an entry might be modified between checking the condition and attempting removal.

Algorithm explanation:

The `removeEntriesIf` method iterates over the `ConcurrentHashMap` using `forEach`. For each entry, it tests the value against the provided `Predicate`. If the predicate returns true, it attempts to remove the entry using `map.remove(key, value)`. This specific `remove` overload is atomic and only removes the entry if the current value associated with the key is equal to the provided `value`. This prevents issues where another thread might have modified the value between the `forEach` iteration and the `remove` call. The time complexity is O(N) where N is the number of entries in the map, as each entry is visited. Space complexity is O(1) beyond the map storage itself. This approach ensures that removals are safe even if other threads are concurrently modifying the map.

Pseudocode:

Class CustomConcurrentMap:
  ConcurrentHashMap map

  method removeEntriesIf(condition):
    for each key, value in map:
      if condition(value) is true:
        atomically remove key if its value is still value

  main method:
    create map
    add entries
    call removeEntriesIf with condition (value is even)
    print map