Java parallel thread: how to wait for threads to complete for a parallel thread?

So, I have a list from which I get a parallel stream to populate the map as follows:

Map<Integer, TreeNode> map = new HashMap<>();
List<NodeData> list = some_filled_list;

//Putting data from the list into the map
list.parallelStream().forEach(d -> {
                TreeNode node = new TreeNode(d);
                map.put(node.getId(), node);
            });

//print out map
map.entrySet().stream().forEach(entry -> {
     System.out.println("Processing node with ID = " + entry.getValue().getId());
                });

The problem with this code is that the card prints when the "data entry" process is still ongoing (because it is parallel), so as a result the card has not yet received all the elements from the list. Of course, in my real code this is not just a printout of the card ; I use a map to take advantage of O (1) search time.

My question is:

  • How to make the main thread wait for the "data delivery" to be completed before the card is printed? I tried putting "put data" inside stream t and doing t.start()and t.join(), but that doesn't help.

  • , ? , parallelism .

+4
3

list.parallelStream().forEach side-effects, Stream.

, , , , " " ( ), , forEach , , . , , HashMap, ... , , HashMap? , , , , / ..

, ConcurrentHashMap , -, - , .

- collect Map forEach:

Map<Integer, TreeNode> map = list.parallelStream()
        .collect(Collectors.toMap(
                NodeData::getId,
                TreeNode::new
        ));

, . , ( ), .

+6

, , .

the "putting data" process is still going on - , , HashMap . ConcurrentHashMap.

+1

, - , - :

    List<NodeData> list = new ArrayList<>();

    //Putting data from the list into the map
    Map<Integer, TreeNode> map = list.parallelStream()
            .collect(Collectors.toMap(
                    n -> n.getId(),
                    n -> new TreeNode(n)
            ));

At least now you have a terminal in the stream. You will use multiple threads, and the display will certainly be complete.

+1
source

Source: https://habr.com/ru/post/1692081/


All Articles