Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asynchronous for loop no hanging

I wrote a synchronous for loop like this:

for (Map.Entry<String, CustomClass> entry : assocs.entrySet()) {
  String key = entry.getKey();
  CustomClass value = entry.getValue();
  value.tick(key);
}

The problem is that sometimes (rarely) .tick hangs. If a single .tick, no big deal, it fixes itself after a while and doesn't actually matter at all (it's due to a client with slow internet). But if it delays the rest of them then it's a problem.

So I want each loop body to run without waiting for other ones to finish.

like image 661
theonlygusti Avatar asked Jan 28 '23 08:01

theonlygusti


1 Answers

Probably the simplest way of parallelising this would be to use parallel streams:

 assocs.entrySet().parallelStream()
     .forEach(e -> e.getValue().tick(e.getKey()));

But be aware that this will use the ForkJoinPool.commonPool to execute your threads, which has one less threads than you've got processors.

If you want to increase the parallelism, you can always run in your own ForkJoinPool

new ForkJoinPool(numberOfThreads).submit(() ->
    assocs.entrySet().parallelStream()
        .forEach(e -> e.getValue().tick(e.getKey())));
like image 199
beny23 Avatar answered Jan 30 '23 21:01

beny23