How to make a defensive copy of a SettableFuture? Or generally a ListenableFuture?

Viewed 77

Like CompletableFuture.copy(). Not sure if it makes sense for other ListenableFutures, but at least for SettableFuture, I don't want an unauthorized client to set the future.

I'm thinking about using Futures.transform(), which seems to create a chained ListenableFuture.

1 Answers

transform(x -> x) is a good solution -- and it sounds like an equivalent one to copy().

The only caveat I can think of is that it's possible for updates to the two Future objects to race: It's possible for the original Future to complete and the other Future to be cancelled, in which case you have a "copy" with a different status. (Similarly, it's possible to observe one Future as completed while the other is still pending.) Again, this sounds like it's the case for copy(), too. If it concerns you, you can create a ForwardingListenableFuture that wraps the original Future instead.

Related