I have a Hashmap where I maintain mapping of different kinds of readers to their respective java class implementations. I have a multithreaded Java server which supports 32 types of readers.
You can assume every 30 seconds, getReader() is called internally by 1000s of objects for each type of reader.
Whenever I reduce the refresh time to 20 seconds, it starts throwing ConcurrentModificationException for some readers sporadically. Is it expected?
What difference does it make with decreasing the time period?
class Mapper {
Map<String, Reader> READER = new HashMap<>();
public static Reader getReader(type) {
Reader reader = READER.computeIfAbsent(type, k -> new ReaderImpl());
}
}
You should use a ConcurrentHashMap if your map can be accessed by multiple Threads.
Whenever I reduce the refresh time to 20 seconds, it starts throwing ConcurrentModificationException for some readers sporadically. Is it expected?
It might be just a coincidence. If you reduce the time, you just make it more probable that Threads will try to access the map and will break it because you are not using a synchronized collection. There is also the possibility that if you run your application enough times you will get the exception also for your 30 seconds refresh time. Debugging multithreaded applications is hard because you might think that your application is running okay - but in the end it turns out that for 1 out of 1000 you get an error because you handled multithreading the wrong way.
As Andy Turner pointed out correctly - you are lucky that ConcurrentModificationException appeared. If you receive no exception that does not mean the problem is not there. It would be worse if you received such error in your application when running in production.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With