0

There is a class as follows:

class Foo {
  private int len;
  public Foo(int l) { this.N = N; }
  public void process(List<Bar> list) {
    int start = 0;
    while(start < list.size()) {
        N = N < list.size()? N : list.size();
        List<Integer> sublist = list.subList(start, N);
        process(sublist);
        start = N;
        N += len;
    }
  
  }
  
  private void handle(List<Bar> sublist) {
    // time consuming code here
  }
}

I would like to parallelise this code because the handle method is time consuming.
I was thinking that an approach could be:

Split the list in lists of size len 
Pass each sublist to an Executor via a Runnable submission per sublist
Have a shared list for storing the results of handle
Make current thread wait till Executor finishes. 

Is there some other constructs that are more suitable for this use case?

Jim
  • 3,845
  • 3
  • 22
  • 47

1 Answers1

0

Let's say you have split a list of values into List<ListInteger>> sublists. Then an easy option to process the sublists concurrently is to use paraller streams:

sublists.parallelStream()
    .forEach(this::handle);

Of course, you have to remember to synchronize all shared resources utilized by handle().

If the case is simpler and a result of processing is simply returned by handle():

sublists.parallelStream()
    .map(this::handle)
    .collect(Collectors.toList());

will process the sublists in parallel and create a list with the results.

Prectron
  • 282
  • 2
  • 11
  • Does this use an executor? – Jim Nov 08 '22 at 23:10
  • @Jim No, the advantage of using parallel streams is that you don't have to explicitly operate on threads. – Prectron Nov 08 '22 at 23:16
  • So is it a thread per sublist? Or a thread processes more than one sublist? – Jim Nov 08 '22 at 23:20
  • A thread poll that has the default size of the number of your cores minus one. Additional details can be found [here](https://stackoverflow.com/questions/30802463/how-many-threads-are-spawned-in-parallelstream-in-java-8). So one thread can process more than one sublist, but that seems good, as creating more threads than you have cores won't help performance. – Prectron Nov 08 '22 at 23:28