📌 Для чего нужен
StructuredTaskScope?StructuredTaskScopeFuture, CompletableFuture и ExecutorService.
import java.util.concurrent.*;
public class StructuredTaskScopeExample {
public static void main(String[] args) throws InterruptedException, ExecutionException {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
// Запускаем две параллельные задачи
var task1 = scope.fork(() -> fetchDataFromAPI("API 1"));
var task2 = scope.fork(() -> fetchDataFromAPI("API 2"));
// Дожидаемся завершения (или отмены в случае ошибки)
scope.join();
scope.throwIfFailed(); // Выбросит исключение, если одна из задач завершилась с ошибкой
// Получаем результаты
String result1 = task1.get();
String result2 = task2.get();
System.out.println("Result 1: " + result1);
System.out.println("Result 2: " + result2);
}
}
private static String fetchDataFromAPI(String apiName) throws InterruptedException {
Thread.sleep(1000); // Имитация задержки запроса
if (Math.random() > 0.8) throw new RuntimeException(apiName + " failed!"); // Имитация ошибки
return apiName + " response";
}
}
#java #concurrency #structuredconcurrency
Please open Telegram to view this post
VIEW IN TELEGRAM
👍14