Atomic execution

I have the following:

HashMap hm =new HashMap()

publicvoid add (String a, String b)

{

hm.put(a,b);

}

is the hm.put(a,b) an atomic call? Otherwise "add" needs to be synchronized in a multithreaded application.

[404 byte] By [lokpesta] at [2007-10-3 4:58:16]
# 1
It's not atomic. It actually even contains a loop. Look at the sources.
CeciNEstPasUnProgrammeura at 2007-7-14 23:03:38 > top of Java-index,Java Essentials,Java Programming...
# 2

This link mentions that read and writes are atomic:

http://java.sun.com/docs/books/tutorial/essential/concurrency/atomic.html

but this might not apply to operations on a HashMap?

if its not atomic I guess its not safe to have multiple threads execute it.

Is there a possibility that the following could happen:

Thread 1 makes add(x,y)

Thread 2 makes add(x,z)

afterwards when looking up x it maps to y, becuause for some reason thread 1 updates x last even though it get executed first.

lokpesta at 2007-7-14 23:03:38 > top of Java-index,Java Essentials,Java Programming...
# 3
You're code shouldn't depend on what order code in different threads get's executed anyway.
malcolmmca at 2007-7-14 23:03:38 > top of Java-index,Java Essentials,Java Programming...
# 4

> I have the following:

>

> > HashMap hm = new HashMap()

>

> public void add (String a, String b)

> {

>hm.put(a,b);

> /code]

> is the hm.put(a,b) an atomic call? Otherwise "add"

> needs to be synchronized in a multithreaded

> application.

IMHO even if it is atomic, if[code]hm.put(a,b);

is not in a synchronized(hm) block, while iterating through Hashmap you might get a ConcurrentModificationException. The iterators returned by collections are fail fast. As somebody mentioned ConcurrentHashmap is a better option and unlike HashTable the performance hit is not that bad either, since it uses lock striping mechanism instead of synchronizing all the methods.

kilyasa at 2007-7-14 23:03:38 > top of Java-index,Java Essentials,Java Programming...