import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
class Entry {
private String id;
private String data;
public Entry(String id, String data) {
this.id = id;
this.data = data;
}
public String getId() {
return id;
}
public String getData() {
return data;
}
}
public class NestedEntries {
public static List<Entry> fetchNestedEntries(int maxEntries, long timeoutMillis) throws TimeoutException {
List<Entry> allEntries = new ArrayList<>();
ExecutorService executor = Executors.newFixedThreadPool(10); // Adjust thread pool size as needed
for (int i = 0; i < maxEntries; i++) {
final int entryId = i; // Capture i for the lambda expression
executor.submit(() -> {
try {
// Simulate an asynchronous operation with a potential delay
Thread.sleep((long) (Math.random() * 1000)); // Simulate work
String data = "Data for entry " + entryId;
allEntries.add(new Entry("entry-" + entryId, data));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
executor.shutdown();
try {
if (!executor.awaitTermination(timeoutMillis, TimeUnit.MILLISECONDS)) {
executor.shutdownNow();
throw new TimeoutException("Timeout occurred while fetching nested entries.");
}
} catch (InterruptedException e) {
executor.shutdownNow();
Thread.currentThread().interrupt();
throw new TimeoutException("Timeout occurred while fetching nested entries.");
}
return allEntries;
}
public static void main(String[] args) {
try {
List<Entry> entries = fetchNestedEntries(10, 500); // Fetch 10 entries with a 500ms timeout
for (Entry entry : entries) {
System.out.println("ID: " + entry.getId() + ", Data: " + entry.getData());
}
} catch (TimeoutException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
Add your comment