Answer the question
In order to leave comments, you need to log in
ExecutorService - how to get data from multiple Callable threads correctly?
There is a class that implements Callable and returns the results of calculations. The calculations themselves last about 2-3 seconds.
It is necessary to continuously endlessly receive the result from this class in 8 threads. The data returned by each thread is in no way dependent on each other. The received data is summarized with each other in the main thread of execution.
Now done like this:
public void run () {
executorService = Executors.newFixedThreadPool(this.threadsCount); // 8 потоков
threadsPool = new ArrayList<>();
for (int i = 0; i < threadsCount; i++) {
threadsPool.add(
executorService.submit(
dataProvider.callback() // возвращает Callable
)
);
}
while (threadsPool.size() > 0) {
startThread();
}
executorService.shutdown();
}
private void startThread () {
try {
dataHandler.callback(
threadsPool.get(0) // отправляем полученные данные на суммирование
);
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
threadsPool.remove(0); // удаляем текущий поток
threadsPool.add(
this.executorService.submit(
dataProvider.callback() // добавляем новый заместо старого
)
);
}
Answer the question
In order to leave comments, you need to log in
Found a solution using CompletitionService.
executorService = Executors.newFixedThreadPool(threadsCount);
completionService = new ExecutorCompletionService<>(executorService);
for (int i = 0; i < threadsCount; i++) {
completionService.submit(
renderDataProvider.callback()
);
}
while (true) {
try {
renderDataHandler.callback(
completionService.take()
);
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
completionService.submit(
renderDataProvider.callback()
);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question