1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.concurrent.ExecutorService;
  4. import java.util.concurrent.Executors;
  5. import java.util.concurrent.TimeUnit;
  6. import java.util.concurrent.TimeoutException;
  7. class Entry {
  8. private String id;
  9. private String data;
  10. public Entry(String id, String data) {
  11. this.id = id;
  12. this.data = data;
  13. }
  14. public String getId() {
  15. return id;
  16. }
  17. public String getData() {
  18. return data;
  19. }
  20. }
  21. public class NestedEntries {
  22. public static List<Entry> fetchNestedEntries(int maxEntries, long timeoutMillis) throws TimeoutException {
  23. List<Entry> allEntries = new ArrayList<>();
  24. ExecutorService executor = Executors.newFixedThreadPool(10); // Adjust thread pool size as needed
  25. for (int i = 0; i < maxEntries; i++) {
  26. final int entryId = i; // Capture i for the lambda expression
  27. executor.submit(() -> {
  28. try {
  29. // Simulate an asynchronous operation with a potential delay
  30. Thread.sleep((long) (Math.random() * 1000)); // Simulate work
  31. String data = "Data for entry " + entryId;
  32. allEntries.add(new Entry("entry-" + entryId, data));
  33. } catch (InterruptedException e) {
  34. Thread.currentThread().interrupt();
  35. }
  36. });
  37. }
  38. executor.shutdown();
  39. try {
  40. if (!executor.awaitTermination(timeoutMillis, TimeUnit.MILLISECONDS)) {
  41. executor.shutdownNow();
  42. throw new TimeoutException("Timeout occurred while fetching nested entries.");
  43. }
  44. } catch (InterruptedException e) {
  45. executor.shutdownNow();
  46. Thread.currentThread().interrupt();
  47. throw new TimeoutException("Timeout occurred while fetching nested entries.");
  48. }
  49. return allEntries;
  50. }
  51. public static void main(String[] args) {
  52. try {
  53. List<Entry> entries = fetchNestedEntries(10, 500); // Fetch 10 entries with a 500ms timeout
  54. for (Entry entry : entries) {
  55. System.out.println("ID: " + entry.getId() + ", Data: " + entry.getData());
  56. }
  57. } catch (TimeoutException e) {
  58. System.err.println("Error: " + e.getMessage());
  59. }
  60. }
  61. }

Add your comment