简体   繁体   中英

How to let multiple threads manipulate one data object in Java

Now I have a HashMap called words and a Producer class that extends Thread class.

And I have a for loop like that:

for (int i = 0; i < 10; i++) {
  Producer producer = new Producer(i);
  producer.run();
}

I want to let each producer add some words into the HashMap words. Does it work if I just put the HashMap<...> words about the for (int....) statement?

It not, what should I do to achieve this?

I'm afraid you don't specify the question precisely enough for it to be answered.

Does it work if I just put the HashMap<...> words about the for (int....) statement?

It almost does; that is, it will indeed create a new hash map (provided that "the words" are right). What it won't do is it won't make sure that has map is synchronized. As @Thilo says in the comment above, there are two easy ways to do so:

  1. ConcurrentHashMap provides you with an easy multithreading-ready map implementation
  2. Collections.synchronizedMap wraps a map of your choice making it ready for a multithreaded environment

Pros and cons of the approaches (and way more) can be found at What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

The ConcurrentHashMap is very similar to the HashMap class, except that ConcurrentHashMap offers internally maintained concurrency. It means you do not need to have synchronized blocks when accessing ConcurrentHashMap in multithreaded application.

//Initialize ConcurrentHashMap instance
ConcurrentHashMap<String, Integer> m = new ConcurrentHashMap<String, Integer>();

//Print all values stored in ConcurrentHashMap instance
for each (Entry<String, Integer> e : m.entrySet())
{
system.out.println(e.getKey()+"="+e.getValue());
}

Above code is reasonably valid in multi-threaded environment in your application. The reason, I am saying “reasonably valid” is that, above code yet provides thread safety, still it can decrease the performance of application. And ConcurrentHashMap was introduced to improve the performance while ensuring thread safety.

To improve it's performace you can adjust following parameters as per your need:

  • initialCapacity

  • loadFactor

  • concurrencyLevel

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM