Hi All I know that a Hashmap object should not be modified in multiple threads - but just on curousity basis - If multiple threads add different values to the hashmap object - but for the same key - is there any chance that the hashmap might contain multiple entries for the same key? I mean is it possible somehow for a hashmap to have mutiple entries for the same key? thanks Anamitra
The Map interface does not allow this directly. But you can create this effect yourself by putting a Collection of values into the Map. When you get() a value, test if (value instanceof Collection) - if so, cast it to Collection and iterate to get the values.
"I'm not back." - Bill Harding, Twister
Rajasekaran Anand
Greenhorn
Joined: Sep 13, 2001
Posts: 23
posted
0
Usually if u try to give multiple entries for the same key the last entry will be the value for that key.That is key will get overriden.So it is adopting one --> one policy.one -->many policy is not achievable upto my knowledge that too directly. Anand
Zakaria Haque
Ranch Hand
Joined: Jan 02, 2002
Posts: 60
posted
0
Very interesting question. From HashMap.put(Object,Object) source in 1.3, it looks like multiple threads can actually put multiple entries in the hashtable with same key !!! Here is the code that adds new entry to the hashtable if there is no entry with the same key already esisting ---- Entry e = new Entry(hash, key, value, tab[index]); tab[index] = e; count++; return null; ---- If there os no entry in the hashtable with the same key and one thread executes upto before this block, and then the other thread starts executing, you will end up with to Entry instances with the same key. !! Please prove me wrong.
tobe bondhu nouka bherao<br />shonabo gaan aj shara raat
Dirk Schreckmann
Sheriff
Joined: Dec 10, 2001
Posts: 7023
posted
0
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
posted
0
Originally posted by Zakaria Haque: Very interesting question. From HashMap.put(Object,Object) source in 1.3, it looks like multiple threads can actually put multiple entries in the hashtable with same key !!!
Yes, they can. There can even happen far nastier things (like count being incremented just once when two entries were inserted). The new Collection classes just don't work properly in a multithreaded environment without proper synchronization.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus