I have a class that extends thread, which has a run method that looks roughly like below.
public void run() {
mapOfConcurrentHashMapType.put(id, this);
while (!terminated) {
try {
//doSomethingWithTimeout30sec()
break;
}
catch (Exception e) {
//Log the exception or break if interrupted
}
// some code to get random time
sleep(randomTime);
// catch interrupted exception and set terminated=true
}
mapOfConcurrentHashMapType.remove(id);
}
Five instances of that thread are created on application startup, and they populate the concurrent hashmap with threads in retry.
After 30 seconds of timeout and exception thrown from doSomething, the threads are in sleep. After this a method is called to check all the threads in retry using forEach as shown below. The problem is that sometimes the map will be missing 1-2 values, this occurs rarely maybe once in 20-25 runs.
While I know that concurrentHashMap iterators are not very consistent (weakly), I would not expect that even after 30 seconds since the values were put in the map and not removed yet. The iterator would not have the updated view.
The missing threads continue to run, and logs are printed, which show the same.
Please advise if I am missing something here.
mapOfConcurrentHashMapType.forEach((key, value) -> {
value.terminated= true;
value.interrupt();
//Log the thread, key and value.
});
7