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.
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.
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.
> 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.