HashMap holding duplicate keys

前端 未结 1 1914
遥遥无期
遥遥无期 2021-01-27 02:00

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

1条回答
  •  有刺的猬
    2021-01-27 02:49

    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.

    0 讨论(0)
提交回复
热议问题