xref: /aosp_15_r20/external/aws-sdk-java-v2/docs/design/UseOfCompletableFuture.md (revision 8a52c7834d808308836a99fc2a6e0ed8db339086)
1**Design:** Convention, **Status:** [Accepted](README.md)
2
3## Use of CompletableFuture
4
5Operations on the asynchronous clients return [`CompleteableFuture<T>`][1] where `T` is the response type for the operation. This is somewhat curious in that [`CompleteableFuture`][1] is a concrete implementation rather than an interface. The alternative to returning a [`CompleteableFuture`][1] would be to return a [`CompletionStage`][2], an interface intended to allow chaining of asynchronous operations.
6
7The key advantage of [`CompleteableFuture`][1] is that it implements both the [`CompletionStage`][2] and [`Future`][3] interfaces - giving users of the SDK maximum flexibility when it comes to handling responses from their asynchronous calls.
8
9Currently [`CompleteableFuture`][1] is the only implementation of [`CompletionStage`][2] that ships with the JDK. Whilst it's possible that future implementations will be added  [`CompletionStage`][2] will always be tied to [`CompleteableFuture`][1] via the  [`#toCompletableFuture`][4] method. Additionally, [`CompleteableFuture`][1] is not a `final` class and thus could be extended if there was a requirement to do so.
10
11One of the perceived risks with exposing [`CompleteableFuture`][1] rather than [`CompletionStage`][2] is that a user of the SDK may spuriously call [`#complete`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#complete-T-) or [`#completeExceptionally`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#completeExceptionally-java.lang.Throwable-) which could cause unintended consequences in their application and the SDK itself. However this risk is also present on the [`CompletionStage`][2] via the [`#toCompletableFuture`][4] method.
12
13If the [`CompletionStage`][2] interface did not have a [`#toCompletableFuture`][4] method the argument for using it would be a lot stronger, however as it stands the interface and its implementation are tightly coupled.
14
15Using [`CompleteableFuture`][1] gives users the best bang for their buck without much additional risk.
16
17[1]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html
18[2]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletionStage.html
19[3]: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html
20[4]: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletionStage.html#toCompletableFuture--
21