Asynchronous for loop not hanging

I wrote a synchronous loop for this type:

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) .tickfreezes. If one .tickdoes not really matter, he corrects himself after a while and does not matter at all (due to a client with slow Internet access). But if it delays the rest, then this is a problem.

So, I want each cycle of the cycle to work without waiting for others to complete.

+4
source share
3 answers

Andrew solution , , 10 ; assocs 10 , , . - ExecutorService :

ExecutorService service = Executors.newCachedThreadPool();

assocs.entrySet().forEach(entry -> {
    service.execute(() -> {
        String key = entry.getKey();
        CustomClass value = entry.getValue();
        value.tick(key);
    );
);
+3

, ExecutorService, :

final ExecutorService exec = Executors.newFixedThreadPool(10);

//create a list of Futures, so you know when each tick is done
final List<Future> futures = new ArrayList<>();
for (final Map.Entry<String, CustomClass> entry : assocs.entrySet()) {
  final Future<?> future = exec.submit(new Runnable() {
    public void run() {
      String key = entry.getKey();
      CustomClass value = entry.getValue();
      value.tick(key);
    }
  });
  futures.add(future);
}

// wait for each future to complete before moving on
for (final Future<?> future : futures) {
  try {
    future.get();
  } catch (Execption e) {
    e.printStackTrace();
  }
}

, . value.tick , , ; Java , , , .

+2

Probably the easiest way to parallelize would be to use parallel threads:

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

But keep in mind that this will use ForkJoinPool.commonPoolto execute your threads, which has fewer threads than you have processors.

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

new ForkJoinPool(numberOfThreads).submit(() ->
    assocs.entrySet().parallelStream()
        .forEach(e -> e.getValue().tick(e.getKey())));
+2
source

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


All Articles