[concurrency-interest] Reusing CompletableFuture

Pavel Rappo pavel.rappo at gmail.com
Sun Jul 24 14:17:55 EDT 2016


In my experience, get() and join() are too precious to lose them and
CompletionStage.toCompletableFuture is too weakly defined (UOE) to be
relied upon. So either people will do everything in an async fashion
or they will come up with some tricks like:

CompletionStage<?> cs = null;
CompletableFuture<?> cf =
CompletableFuture.completedFuture(null).thenCompose(x -> cs);

On Sun, Jul 24, 2016 at 7:07 PM, Viktor Klang <viktor.klang at gmail.com> wrote:
> A possible solution is to return CompletionStage rather than
> CompletableFuture.
>
> --
> Cheers,
>>
>
> On Jul 24, 2016 18:23, "Martin Buchholz" <martinrb at google.com> wrote:
>>
>> Don't reuse CompletableFutures.
>> Most obviously because they're mutable.
>>
>> See also https://bugs.openjdk.java.net/browse/JDK-8161600
>>
>> On Sun, Jul 24, 2016 at 5:57 AM, Pavel Rappo <pavel.rappo at gmail.com>
>> wrote:
>>>
>>> Hi,
>>>
>>> Is it generally safe to reuse an instance of CompletableFuture? Or am I
>>> risking
>>> with memory leaks due to dependants build up?
>>>
>>> Say, I have a method that returns a CF. In some cases it may return a CF
>>> straight away indicating that the action has been already done. Should I
>>> always
>>> create a new completed CF, or can I reuse a pre-cached one?
>>>
>>> There's a comment in the class itself, but I'm not sure I understand it
>>> enough
>>> to make a conclusion:
>>>
>>>      * ...Without precautions, CompletableFutures would be prone to
>>>      * garbage accumulation as chains of Completions build up, each
>>>      * pointing back to its sources. So we null out fields as soon as
>>>      * possible.  The screening checks needed anyway harmlessly ignore
>>>      * null arguments that may have been obtained during races with
>>>      * threads nulling out fields.  We also try to unlink non-isLive
>>>      * (fired or cancelled) Completions from stacks that might
>>>      * otherwise never be popped: Method cleanStack always unlinks non
>>>      * isLive completions from the head of stack; others may
>>>      * occasionally remain if racing with other cancellations or
>>>      * removals...
>>>
>>> Thanks,
>>> -Pavel
>>> _______________________________________________
>>> Concurrency-interest mailing list
>>> Concurrency-interest at cs.oswego.edu
>>> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
>>
>>
>>
>> _______________________________________________
>> Concurrency-interest mailing list
>> Concurrency-interest at cs.oswego.edu
>> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
>>
>


More information about the Concurrency-interest mailing list