1. import java.util.concurrent.*;
  2. import java.util.function.Supplier;
  3. public class ApiPerformanceTest {
  4. /**
  5. * Measures the performance of an API endpoint with a timeout.
  6. *
  7. * @param endpoint The supplier that provides the API endpoint.
  8. * @param timeoutMs The timeout in milliseconds.
  9. * @return The result of the API call, or null if an error occurred or timeout.
  10. */
  11. public static Object measureApiPerformance(Supplier<Object> endpoint, long timeoutMs) {
  12. ExecutorService executor = Executors.newSingleThreadExecutor();
  13. Future<Object> future = executor.submit(() -> {
  14. try {
  15. return endpoint.get(); // Execute the API endpoint
  16. } catch (Exception e) {
  17. // Handle exceptions (e.g., network errors, API errors)
  18. System.err.println("Error during API call: " + e.getMessage());
  19. return null; // Or throw, depending on desired behavior
  20. }
  21. });
  22. try {
  23. return future.get(timeoutMs, TimeUnit.MILLISECONDS); // Wait for the result with a timeout
  24. } catch (TimeoutException e) {
  25. System.err.println("API call timed out after " + timeoutMs + "ms.");
  26. return null; // Indicate timeout
  27. } finally {
  28. executor.shutdown(); // Shut down the executor
  29. }
  30. }
  31. public static void main(String[] args) {
  32. // Example usage:
  33. Supplier<String> myApiEndpoint = () -> {
  34. try {
  35. // Simulate an API call with a delay
  36. Thread.sleep(500);
  37. return "API Response";
  38. } catch (InterruptedException e) {
  39. Thread.currentThread().interrupt();
  40. return null;
  41. }
  42. };
  43. Object result = measureApiPerformance(myApiEndpoint, 1000);
  44. if (result != null) {
  45. System.out.println("API Response: " + result);
  46. } else {
  47. System.out.println("API call failed or timed out.");
  48. }
  49. }
  50. }

Add your comment