Strange HashMap exception (HashMap$Node cannot be cast to HashMap$TreeNode) Strange HashMap exception (HashMap$Node cannot be cast to HashMap$TreeNode) java java

Strange HashMap exception (HashMap$Node cannot be cast to HashMap$TreeNode)


I also found the same exception with your code. I added a synchronized modifier on the putEntriesToMap() method, and the error seemed to stop occurring. The problem is that both threads are modifying the same map at once. There is an object that must be converted to put the entry in. However, the second thread is dealing with a mutated object, which throws a ClassCastException. So, make sure that no two threads are accessing the same map at once. The synchronized modifier stops all other threads from doing anything with the class/instance if another thread is doing the same. Synchronized static methods synchronize the class itself, whereas synchronized non-static methods only synchronize the instance of the class.


I was getting the same ClassCastException with concurrent calls to HashMap.computeIfAbsent. I fixed by changing the implementation to use ConcurrentHashMap.


I resolved this just making clean and build to the project, and it works