Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CompletableFuture and Garbage Collection

I'd like to fire many one-off async CompletableFutures, like so:

for (Job job : jobs) {
 CompletableFuture.supplyAsync(() -> job.process())
   .whenComplete(this::doSomething);
}

Ideally these CompletableFutures could be garbage collected after whenComplete has finished. But is there a risk they are collected beforehand, since I'm not storing a reference?

like image 825
kantianethics Avatar asked Feb 15 '19 17:02

kantianethics


1 Answers

You're not explicitly storing a reference, but supplyAsync is, internally. The method creates a CompletableFuture and submits a task to the ForkJoinPool (if you're using the common pool) that has a reference back to it. The CompletableFuture returned by whenComplete becomes a dependent on that first CompletableFuture and so is also referenced.

All these objects will be available for garbage collection once the ForkJoinPool completes execution of the Supplier, marks the first CompletableFuture as complete, triggers the second CompletableFuture, and executes the BiConsumer passed to whenComplete.

You're safe.

like image 178
Sotirios Delimanolis Avatar answered Nov 08 '22 13:11

Sotirios Delimanolis