aspose file tools*
The moose likes Threads and Synchronization and the fly likes Example of a Map that fails in concurrent environment Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Example of a Map that fails in concurrent environment" Watch "Example of a Map that fails in concurrent environment" New topic
Author

Example of a Map that fails in concurrent environment

Swerrgy Smith
Ranch Hand

Joined: Mar 26, 2010
Posts: 91
Hi all,

People says that HashMap will not work in a concurrent environment because its methods are not synchronized.
I would like to have a real example about that. I have tried to have multiple threads working with a HashMap but nothing special happened.

Can anyone help me?
Anayonkar Shivalkar
Bartender

Joined: Dec 08, 2010
Posts: 1507
    
    5

Hi Swerrgy,

Reproducing a threading issue is not very easy.

That given, the easiest way to do this would be - to make lot of structural changes (put values to same key, remove same key) via multiple threads. You just may find some unwanted behavior (e.g. remove for single key returning actual value in more than one threads, or after too much remove execution, size goes to -1 instead of 0 etc.).

The simplest way to do this is - extend HashMap class, override critical methods like get, put, remove etc. with exactly same code. The only difference would be - new methods would have arbitrary calls to Thread.sleep (especially when iterating in loops, or dealing with size etc.) - this way, there is a better possibility to run into some thread related issue.

I hope this helps.


Regards,
Anayonkar Shivalkar (SCJP, SCWCD, OCMJD, OCEEJBD)
Muhammad Khojaye
Ranch Hand

Joined: Apr 12, 2009
Posts: 449

Swerrgy Smith wrote:Hi all,
I would like to have a real example about that. I have tried to have multiple threads working with a HashMap but nothing special happened.
Can anyone help me?

I agree with Anayonkar. MultiThreading issues are not easy to reproduce as it depends on exact timing. However, You can think of scenarios where you class is threadsafe or not
Consider below example,

Let suppose two threads A and B execute above method at the same time. A first finds that instance is null, it will instantiate the object. B also finds that instance is null and it will instantiate different object. Both threads will received different results which was not suppose to perform by above method.


http://muhammadkhojaye.blogspot.com/
Bijoy Joseph
Greenhorn

Joined: May 22, 2013
Posts: 4
If you try to remove an entry from a HashMap while it is iterating , you will definitely get ConcurrentModificationException. For example :

import java.util.*;
import java.util.Map.Entry;

public class HashMapSample {

private Map<String,String > map = null;

public HashMapSample() {

map = new HashMap();

}

public void addItems() {

map.put("1","Road");
map.put("2","Car");
map.put("3","Bus");
map.put("4","Truck");

}

public void iterate() {

Set<Entry<String, String>> set = map.entrySet();
Iterator<Entry<String, String>> i = set.iterator();
System.out.println("Size of map :"+map.size());
while (i.hasNext()) {
Entry<String, String> entry = i.next();
map.remove(entry.getKey());

}
System.out.println("Now size : "+map.size());

}



public static void main(String[] args) {

HashMapSample sample = new HashMapSample();
sample.addItems();
sample.iterate();

}

}

If you replace the Map initialization by : map = new ConcurrentHashMap<String, String>(); the exception will go. This is the simplest example to demonstrate the ConcurrentModificationException in HashMap.

For more details :
http://www.coderpanda.com/concurrent-collections/

Dieter Quickfend
Bartender

Joined: Aug 06, 2010
Posts: 543
    
    4

You heard wrong. HashMap may well work fine in a concurrent environment, and synchronization of a Map's method is no guarantee that your application is thread safe.

thread safety must be judged on a case per case basis, and a synchronized collection is rather rarely the way to go.


Oracle Certified Professional: Java SE 6 Programmer && Oracle Certified Expert: (JEE 6 Web Component Developer && JEE 6 EJB Developer)
 
jQuery in Action, 2nd edition
 
subject: Example of a Map that fails in concurrent environment