Java 8 parallel stream of list of method param

前端 未结 3 1451
无人共我
无人共我 2021-01-15 09:09

I have a method:

invokList(List list);


This method is inside a jar and I have no access to the source code of it. So for that

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-15 09:25

    Looks very verbose, but you can try the following. The runAsync() method will make the list chunks run in parallel.

    private void test(List list, int chunkSize) throws ExecutionException, InterruptedException {
        AtomicInteger prev = new AtomicInteger(0);
        List futures = new ArrayList<>();
        IntStream.range(1, (int) (chunkSize * (Math.ceil(Math.abs(list.size() / (double) chunkSize)))))
                .filter(i -> i % chunkSize == 0 || i == list.size())
                .forEach(i -> {
                    List chunk = list.subList(prev.get(), i);
                    futures.add(CompletableFuture.runAsync(() -> invokeList(chunk)));
                    prev.set(i);
                });
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get();
    }
    
    private void invokeList(List list) {
        System.out.println("Invoked for: " + list);
    }
    
    
    

    I ran it for a list of 30 integers, with a chunk size of 5 like this:

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        List list = IntStream.range(0, 30).mapToObj(i1 -> (Object) String.valueOf(i1)).collect(Collectors.toList());
        int chunkSize = 5;
        new Test().test(list, chunkSize);
    }
    
    
    

    Output:

    Invoked for: [15, 16, 17, 18, 19]
    Invoked for: [0, 1, 2, 3, 4]
    Invoked for: [5, 6, 7, 8, 9]
    Invoked for: [10, 11, 12, 13, 14]
    Invoked for: [20, 21, 22, 23, 24]
    

    提交回复
    热议问题