Sobes.tech
Senior

How to implement parallel calls in Java 17 without virtual threads?

sobes.tech AI

Answer from AI

In Java 17, without using virtual threads (Project Loom), traditional tools from java.util.concurrent are usually used for parallel calls.

Main approaches:

  1. ExecutorService — a thread pool for managing parallel tasks.
  2. CompletableFuture — a convenient API for asynchronous programming and combining results.

Example using CompletableFuture:

import java.util.concurrent.*;

public class ParallelCallsExample {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(4);

        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            // simulate a long operation
            sleep(1000);
            return "Result 1";
        }, executor);

        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            sleep(500);
            return "Result 2";
        }, executor);

        // wait for both results
        CompletableFuture<Void> all = CompletableFuture.allOf(future1, future2);
        all.join();

        System.out.println(future1.get());
        System.out.println(future2.get());

        executor.shutdown();
    }

    private static void sleep(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

This approach allows running tasks in parallel, managing the thread pool, and processing results asynchronously.

How to implement parallel calls in Java 17 without… - sobes.tech