S
S
SankaSanka2021-03-15 15:07:48
Java
SankaSanka, 2021-03-15 15:07:48

How to parallelize work with the map?

there is a method that takes a set, works with it, gets two results and writes them to the map.
I want to split the process of obtaining results into two threads.
here is what I have now:

public class IndexedThread implements Runnable {
  private final Set<String> strSet;

  public IndexedThread(Set<String> strSet) {
    this.strSet = strSet;
  }
  @Override
  public void run() {
    for (String s : strSet) {
         //работаем работу
}
    map.put(str, newstr);
    }
}


private Map<String, String> makework(Set<String> wordFromFile) {
        Map<String, String> map = new ConcurrentHashMap<String, String>();
IndexedThread thread = new IndexedThread(str);
               thread.start();

 for (String str : wordFromFile) {
//работаем другую работу
map.put(str, newstr2);
}
return map;
}


how to complete it humanly please tell me.
The 2 "works" in the method are not connected in any way.
2 different actions need to be done with each element of the set.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2021-03-15
@SankaSanka

In java 8+ multithreading is achieved in a much clearer and simpler way:

// Java 11
public class ParallelMapDemo {

    public static void main(String[] args) {
        var inputSet = Set.of(1, 2, 3, 4, 5);

        var result = inputSet.parallelStream()
                .collect(Collectors.toMap(Function.identity(), ParallelMapDemo::doSomething));
    }

    static String doSomething(Integer i) {
        //  Do Something
        return i.toString();
    }

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question