While experimenting with HashMap
, I noticed something weird.
Ran 4 threads with each trying to put (key,value) with keys from 0 to 9999, value a constant st
HashMap is not thread safe, as explicitly noted in the linked docs. You are providing a good example of why this is so. Yes, you are putting in duplicate keys because put
does not check that another thread is putting the same key in. That is what it means not to be thread safe.
The retrieval behavior is undefined, so it can return whichever value it wants at that point. It is probably very implementation, platform and even timing-dependent.
There are a couple of workarounds. The one suggested in the docs is
Map m = Collections.synchronizedMap(new HashMap(...));
Another option is to use ConcurrentHashMap, which is explicitly designed for the purpose.