|
| 1 | +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | +package com.amazonaws.lambda.durable.examples; |
| 4 | + |
| 5 | +import com.amazonaws.lambda.durable.DurableContext; |
| 6 | +import com.amazonaws.lambda.durable.DurableFuture; |
| 7 | +import com.amazonaws.lambda.durable.DurableHandler; |
| 8 | +import java.time.Duration; |
| 9 | +import java.util.ArrayList; |
| 10 | + |
| 11 | +/** |
| 12 | + * Performance test example demonstrating concurrent async steps. |
| 13 | + * |
| 14 | + * <p>This example tests the SDK's ability to handle many concurrent operations: |
| 15 | + * |
| 16 | + * <ul> |
| 17 | + * <li>Creates async steps in a loop |
| 18 | + * <li>Each step performs a simple computation |
| 19 | + * <li>All results are collected and summed |
| 20 | + * </ul> |
| 21 | + */ |
| 22 | +public class ManyAsyncStepsExample extends DurableHandler<ManyAsyncStepsExample.Input, String> { |
| 23 | + |
| 24 | + private static final int STEP_COUNT = 500; |
| 25 | + |
| 26 | + public record Input(int multiplier) {} |
| 27 | + |
| 28 | + @Override |
| 29 | + public String handleRequest(Input input, DurableContext context) { |
| 30 | + var startTime = System.currentTimeMillis(); |
| 31 | + var multiplier = input.multiplier() > 0 ? input.multiplier() : 1; |
| 32 | + |
| 33 | + context.getLogger().info("Starting {} async steps with multiplier {}", STEP_COUNT, multiplier); |
| 34 | + |
| 35 | + // Create 100 async steps |
| 36 | + var futures = new ArrayList<DurableFuture<Integer>>(STEP_COUNT); |
| 37 | + for (var i = 0; i < STEP_COUNT; i++) { |
| 38 | + var index = i; |
| 39 | + var future = context.stepAsync("compute-" + i, Integer.class, () -> index * multiplier); |
| 40 | + futures.add(future); |
| 41 | + } |
| 42 | + |
| 43 | + context.getLogger().info("All {} async steps created, collecting results", STEP_COUNT); |
| 44 | + |
| 45 | + // Collect all results |
| 46 | + var totalSum = 0L; |
| 47 | + for (var future : futures) { |
| 48 | + totalSum += future.get(); |
| 49 | + } |
| 50 | + |
| 51 | + var executionTimeMs = System.currentTimeMillis() - startTime; |
| 52 | + context.getLogger() |
| 53 | + .info("Completed {} steps, total sum: {}, execution time: {}ms", STEP_COUNT, totalSum, executionTimeMs); |
| 54 | + |
| 55 | + // Wait 10 seconds to test replay |
| 56 | + context.wait("post-compute-wait", Duration.ofSeconds(10)); |
| 57 | + |
| 58 | + return String.format("Completed %d async steps. Sum: %d, Time: %dms", STEP_COUNT, totalSum, executionTimeMs); |
| 59 | + } |
| 60 | +} |
0 commit comments