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.
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())));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With