Junior — Middle
Can you give an example of a situation where you had to organize sequential or parallel processes in a project?
sobes.tech AI
Answer from AI
In one of my Java projects, I needed to organize the sequential execution of several tasks, where the result of one task influenced the next. For this, I used a chain of CompletableFuture to perform operations asynchronously while ensuring the order.
Example:
CompletableFuture.supplyAsync(() -> fetchData())
.thenApply(data -> processData(data))
.thenAccept(result -> saveResult(result));
In another case, I needed to run several independent tasks in parallel and wait for their completion. For this, I used ExecutorService with a thread pool and the invokeAll method:
ExecutorService executor = Executors.newFixedThreadPool(3);
List<Callable<String>> tasks = Arrays.asList(task1, task2, task3);
List<Future<String>> results = executor.invokeAll(tasks);
// process results
executor.shutdown();
This approach allowed me to efficiently manage parallelism and control the execution sequence where necessary.