I have a block of code that should be run in parallel on different threads using CompletableFuture
and ExecutorService
. The block of code makes network requests (Using RetroFit), and waits for each network request to finish before going on to make the next request, etc. Can I call SingleThreadExecutor#submit()
multiple times, passing around that executor?
I want to ensure all parallel runs of this block of code get their own thread and run all their operations on that thread.
Basically the block of code should act like synchronous code, but have multiple instance of this block running in parallel, each instance on it's own thread.
Currently, the program just idles when we make a call from the Service
and I suspect it has to do with passing around the same SingleThreadExecutor
but am a bit stuck.
ArrayList<CompletableFuture<Void>> futures = new ArrayList<>();for (int i = 0; i < SIZE; i++) { ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { Future<List<String>> stringListFuture = myStringService.getStringList(executor); // We begin stalling once the next line gets hit. List<String> stringList = stringListFuture.get(); Future<Integer> integerDataFuture = myIntegerService.getInteger(executor); Integer integerData = integerDataFuture.get(); executor.shutdown(); }, executor); futures.add(future);}CompletableFuture<Void> completableFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); completableFutures.join();// Do something after all blocks of code have finished running in parallel.
class MyStringFuture { public Future<List<String>> getStringList(ExecutorService executor) { // Could these nested uses of the same executor be the problem? Future<Double> doubeDataFuture = doubleDataService.getFuture(); Double doubleData = doubeDataFuture.get(executor); Call<List<Dividend>> data = retrofit.create(Api.class).getData(doubleData); return executor.submit(() -> data.execute().body()); }}