I am using CompletableFuture to publish events. Since there is a requirement that the order of the events need to be maintained, I am chaining them by key using thenCompose. I am concerned about garbage collection with such an approach using infinite chaining. Will additional calls maintain references to previous CompletableFuture and not allow for them to ever be garbage collected?
Map<Integer, CompletableFuture<EventResult>> eventFutureMap = new HashMap<>();
Publisher publisher;
public CompletableFuture<EventResult> publish(Event event) {
CompletableFuture<EventResult> eventFuture;
Integer key = event.getKey();
CompletableFuture<EventResult> existingEvent = eventFutureMap.get(key);
if (existingEvent != null) {
eventFuture = existingEvent.thenCompose((EventResult meta) -> publisher.publish(event));
} else {
eventFuture = publisher.publish(event);
}
eventFutureMap.put(key, eventFuture);
return eventFuture;
}