import java.util.concurrent.*;
import java.util.function.Supplier;
public class ApiPerformanceTest {
/**
* Measures the performance of an API endpoint with a timeout.
*
* @param endpoint The supplier that provides the API endpoint.
* @param timeoutMs The timeout in milliseconds.
* @return The result of the API call, or null if an error occurred or timeout.
*/
public static Object measureApiPerformance(Supplier<Object> endpoint, long timeoutMs) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Object> future = executor.submit(() -> {
try {
return endpoint.get(); // Execute the API endpoint
} catch (Exception e) {
// Handle exceptions (e.g., network errors, API errors)
System.err.println("Error during API call: " + e.getMessage());
return null; // Or throw, depending on desired behavior
}
});
try {
return future.get(timeoutMs, TimeUnit.MILLISECONDS); // Wait for the result with a timeout
} catch (TimeoutException e) {
System.err.println("API call timed out after " + timeoutMs + "ms.");
return null; // Indicate timeout
} finally {
executor.shutdown(); // Shut down the executor
}
}
public static void main(String[] args) {
// Example usage:
Supplier<String> myApiEndpoint = () -> {
try {
// Simulate an API call with a delay
Thread.sleep(500);
return "API Response";
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return null;
}
};
Object result = measureApiPerformance(myApiEndpoint, 1000);
if (result != null) {
System.out.println("API Response: " + result);
} else {
System.out.println("API call failed or timed out.");
}
}
}
Add your comment